skip to Main Content

Sorry if the title doesn’t make sense, hopefully this does:

<tr>
    <td>
        Cell 1
    </td>
    <td>
        <a href='url1'>Hyperlink 1</a>
    </td>
</tr>
<tr>
    <td>
        Cell 2
    </td>
    <td>
        <a href='url2'>Hyperlink 2</a>
    </td>
</tr>

I am trying to set the onClick event for the first td based on the a from the 2nd td.

My best attempt so far is:

$('tr td:first-of-type').attr('onClick', 'window.location = ' + $(this).next('td > a').attr('href'));

That line sets the window.location attribute but returns an undefined location:
<td onclick="window.location = undefined">

Any tips?

2

Answers


  1. I think your approach is almost correct but there is a small issue with the context of $(this) within the .attr() function. You need to use a function callback to correctly reference the element you want. You can simplify the selector to directly target the ‘a’ element within the second ‘td’. Like This:

    $('tr td:first-of-type').click(function() {
        window.location = $(this).next('td').find('a').attr('href');
    });
    
    Login or Signup to reply.
  2. Your logical mistake is here:

    $(this).next('td > a')
    

    Since this will be a td, next('td > a') is trying to find a sibling element a (since td > a will always select an a).

    a though will never be a sibling of td. I know you’re trying to mitigate this by providing the child selector td > a here, but that’s not how it works:

    .next()

    Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.
    https://api.jquery.com/next/

    Instead, I’d rather use this approach:

    $(this).closest('tr').find('a')
    

    This approach is a little more robust than

    $(this).next('td').find('a')
    

    because it won’t fail if you ever insert additional columns or the order of the table cells changes.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search