Search code examples
javascripthyperlinkclickgreasemonkeytampermonkey

Autoclick JavaScript link in Table


So I've got this HTML Table as follows:

<tbody>
    <tr>
        <td><a href="link1"></td>
        <td><a href=link2"></td>
    <tr>
        <td><a href="link3"></td>
        <td><a href=link4"></td>
   </tr>
</tbody>

It has many more rows than this but this is just a section for the purpose of my question. I know Javascript uses .click to click on links, but I am wondering if there is any way to select the link in the first row first column, because on different web pages the first link in the first column will be different than the one on this page. If this is possible how do I do so? Thank you so much. I looked into this trying to find the answer on my own and I didn't find one. If it helps, I am using Tampermonkey to run the script. Thank you for your help!

Lucy


Solution

  • This will return you first link from the table

    document.querySelector('table a')
    

    if you want first link from the webpage then use

    document.querySelector('a')
    

    If you want to click on it then

    document.querySelector('table a').click()
    

    Or if you want to open in different window then,

    window.open(document.querySelector('table a').href)
    
    document.querySelector('#profile_creatures table a').click()