Question

Based on this HTML tag, how can I click on View from TrustedMachines?

I know how to do it from document.getElementById or name but not sure how to do it this cases

<td>
    <a data-auto-test-id="ViewTrustedMachines" href="/WebObjects/support.woa/wo/iKK52GLbH8yXxkrGGvN4M/4.4.5.53.7.5.0.447.0.0.1">View</a>
</td>

More complete tag:

<tbody>
    <tr>
        <th>Geo</th>
        <td>USA</td>
    </tr>
    <tr>
        <th>Download Queue</th>
        <td>0</td>
    </tr>
    <tr>
        <th>Wish List</th>
        <td>0</td>
    </tr>

    <tr>
        <th>Something else</th>
        <td>
            <a data-auto-test-id="ViewSomethingelse" href="/WebObjects/support.woa/wo/iKK52GLbH8yXxkrGGvN4M/4.4.5.15.1.7.0.142.0.0.1">View</a>
        </td>
    </tr>

    <tr>
        <th>Trusted Machines</th>
        <td>
            <a data-auto-test-id="ViewTrustedMachines" href="/WebObjects/support.woa/wo/iKK52GLbH8yXxkrGGvN4M/4.4.5.53.7.5.0.447.0.0.1">View</a>
        </td>
    </tr>

Here is my normal click for id:

tell application "Safari"
    do JavaScript "document.getElementById('ViewTrustedMachines').click();" in tab 1 of window 1
end tell
Was it helpful?

Solution

Don't use getElementById. Its a pain in the a** and almost never works for what you want. Additionally none of your elements actually have id's so theres no point in use it. Instead use JavaScripts beautiful and helpful querySelector. You can use CSS selectors to selector a single element and do what ever you want from there.

The element you are trying to select has a unique data attribute. The data attribute is data-auto-test-id= and the content of that attribute is ViewTrustedMachines so we can select it simply with document.querySelector('a[data-auto-test-id="ViewTrustedMachines"]'). Finally we just add the .click() to...well...click it.

tell application "Safari"
   do JavaScript "document.querySelector('a[data-auto-test-id=\"ViewTrustedMachines\"]').click();"
end tell

Also correct your HTML:

<table>


    <tbody>
        <tr>
            <th>Geo</th>
            <td>USA</td>
        </tr>
        <tr>
            <th>Download Queue</th>
            <td>0</td>
        </tr>
        <tr>
            <th>Wish List</th>
            <td>0</td>
        </tr>

        <tr>
            <th>Something else</th>
            <td>
                <a data-auto-test-id="ViewSomethingelse" href="/WebObjects/support.woa/wo/iKK52GLbH8yXxkrGGvN4M/4.4.5.15.1.7.0.142.0.0.1">View</a>
            </td>
        </tr>

        <tr>
            <th>Trusted Machines</th>
            <td>
                <a data-auto-test-id="ViewTrustedMachines" href="/WebObjects/support.woa/wo/iKK52GLbH8yXxkrGGvN4M/4.4.5.53.7.5.0.447.0.0.1">View</a>
            </td>
        </tr>
        </tbody>
        </table>

Finally, here's a fiddle to show it in action.

Licensed under: CC-BY-SA with attribution
Not affiliated with apple.stackexchange
scroll top