- How to check if the parent element of an element is in itself the last child with javascript or 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
- }
- });
- <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>
- if (!thisTbody.nextAll('tbody[data-state]')[0]) {
- // It's the last `tbody` with a `data-state` attribute in its
- // enclosing table
- }
- $(document).delegate('a[data-view="showhide"]', 'click', function (e) {
- var thisElem = $(this),
- thisTbody = thisElem.closest('tbody[data-state]'),
- thisIndex = thisTbody.index(),//get the index of the currently selected `tbody` element
- thisCount = thisElem.closest('table').find('tbody[data-state]').length;//get the number of `tbody` elements with the `data-state` attribute
- e.preventDefault();
- //see if the current index is equal to the total number of `tbody[data-state]` elements (remember that `.length` starts at one)
- if (thisIndex == (thisCount - 1)) { /*It has been found that this is the last element*/ }
- });
- <table>
- <tbody class="closed">
- <tr><td><a href="#" class="showhide">cell 1</a></td></tr>
- </tbody>
- <tbody class="closed">
- <tr><td><a href="#" class="showhide">cell 2</a></td></tr>
- </tbody>
- <tbody class="closed">
- <tr><td><a href="#" class="showhide">cell 3</a></td></tr>
- </tbody>
- <tbody>
- <tr><td>cell not important</td></tr>
- </tbody>
- </table>
- $(document).delegate('a.showhide', 'click', function (e) {
- var thisElem = $(this),
- thisTbody = thisElem.closest('tbody.closed'),
- thisIndex = thisTbody.index(),
- thisCount = thisElem.closest('table').find('tbody.closed');
- e.preventDefault();
- //check to see if this element's parent is a last child
- if (thisIndex == (thisCount - 1)) { /*It has been found that this is the last element*/ }
- });