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
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:
Your logical mistake is here:
Since
this
will be atd
,next('td > a')
is trying to find a sibling elementa
(sincetd > a
will always select ana
).a
though will never be a sibling oftd
. I know you’re trying to mitigate this by providing the child selectortd > a
here, but that’s not how it works:Instead, I’d rather use this approach:
This approach is a little more robust than
because it won’t fail if you ever insert additional columns or the order of the table cells changes.