I have a script working to show hide the next() tbody element when another link is clicked, but it’s uuuugly, and I’m sure I could do it more efficiently. Specifically I dont like using 4 parent() calls! Is there a better way to traverse things than that?
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Pooey long jQuery example</title>
</head>
<body>
<table class="thin">
<tbody class="shown_rows">
<tr>
<td><span>td1</span></td>
<td><span>td2</span></td>
<td><span><a href="#" class="do-thing">Show</a></span></td>
</tr>
</tbody>
<tbody class="hidden_rows">
<tr>
<td colspan="7"><span>Temp txt</span></td>
</tr>
</tbody>
<tbody class="shown_rows">
<tr>
<td><span>td1</span></td>
<td><span>td2</span></td>
<td><span><a href="#" class="do-thing">Show</a></span></td>
</tr>
</tbody>
<tbody class="hidden_rows">
<tr>
<td colspan="7"><span>Temp txt</span></td>
</tr>
</tbody>
</table>
</body>
</html>
CSS:
table td {border: 1px solid black;padding:2px;}
table .shown_rows * span {
width:100px; display:block
}
jQuery:
$(".hidden_rows").hide();
$(".do-thing").click(function(e) {
$(this).parent().parent().parent().parent().next("tbody").toggle("fast");
});
jSFiddleydeeee:
This example on jsFiddle
Any thoughts?
(Note, I’m using spans on purpose, and this is a simplified example for the question only so it looks horrid in FF and IE.
Yes, use
closestto go up the tree to the nearest element that matches a selector, then.Note that
next('tbody')could almost certainly be shortened tonext(), since you don’t havetheadortfootelements.