How can I check if the parent, with a certain data attribute, of the element I’m clicking is a ‘last child’ itself? Basically, bearing in mind that they gonna be generated, most of the <tbody>‘s have a data attribute – data-state="closed" – and I wanna check if one of them is the last one when I click on a child element, which is a link, that’s inside it.
JS/jquery:
$('body').delegate('a[data-view="showhide"]', 'click', function (e) {
var thisElem = $(this),
thisTbody = thisElem.closest('tbody');
e.preventDefault();
//check to see if this element's parent is a last child
if (thisTbody.filter('[data-state]').is(':last')) {
console.log('this is the last tbody of its kind called \'data-state\'');
//...Do something
}
});
HTML:
<table>
<tbody data-state="closed">
<tr><td><a href="#" data-view="showhide">cell 1</a></td></tr>
</tbody>
<tbody data-state="closed">
<tr><td><a href="#" data-view="showhide">cell 2</a></td></tr>
</tbody>
<tbody data-state="closed">
<tr><td><a href="#" data-view="showhide">cell 3</a></td></tr>
</tbody>
<tbody>
<tr><td>cell not important</td></tr>
</tbody>
</table>
Many thanks
I’d probably use
nextAll:Or if you know that all of the
tbodyelements that have adata-stateattribute are next to each other (e.g., that last one that doesn’t have one is always at the end), you could just usenext('tbody[data-state]')rather thannextAll('tbody[data-state]'). But it doesn’t really buy you much, and it adds the assumption.