Search code examples
javascripthtmlgreasemonkeyhref

Getting the href from <a> tag within tables


I'm writing a Greasemonkey script, which redirects the user if there's only one search result to that one page. I'm trying to get the link from a table, which has many parent tables. That part of the page that I'm trying to get the link from looks like this:

<tr class="odd">
<td class="name first">
    <a href="need this one">Text</a>
</td>

Tried document.getElementById('name first'), but still no success. I need help without any external libraries. The page has a design of darkening the background of even cells, so if there's no class called 'even' then it assumes that there's only one result, and that part works correctly.


Solution

  • Based on the target page and your apparent purpose (follow the first result link, if there are is only one search result), the code you want is this:

    var EvenRow = document.querySelector ("table.listing tr.even");
    if (EvenRow == null)
    {
        var ResultLink  = document.querySelector ("table.listing tr.odd td.name.first a");
        if (ResultLink != null)
            window.location.href = ResultLink.href;
    }
    


    Notes:

    1. There are multiple nodes with both the "name" and "first" classes. This is the reason for the more specific selector. It's also the reason why Nathan's answer failed (he ignored the tr.odd, for some reason).

    2. A checkExistOfEven() function is not needed.

    3. In this case, you probably want window.location.href = rather than window.location.replace(). The former preserves the search-results page in the history, in case there is some hiccup.