thecommonthread thecommonthread - 1 month ago 8
jQuery Question

jquery get previous column class in separate row

I have a table similar to this (I've created a simpler example here):

<table>
<tr>
<td colspan="4" class="topic">Topic Name</td>
</tr>
<tr>
<td><a href="#">link</a></td>
<td><a href="#">link</a></td>
<td><a href="#">link</a></td>
<td><a href="#">link</a></td>
</tr>
<tr>
<td><a href="#">link</a></td>
<td><a href="#">link</a></td>
<td><a href="#">hello world</a></td>
<td><a href="#">link</a></td>
</tr>
</table>


This is an example table with three rows and four columns. What jQuery code do I use to get the text() in the first td with the class "topic" calling from the td with the text "hello world"?

Answer

You can use closest to traverse up through the DOM

$("td").on("click", function(){
    $(this).closest("table").find("td.topic").first().text()
});