I'm trying to find the ID (test1, test2, test3 etc..) of the next instance of a specific class (findMe).
Here is my code: HTML:
<div >
<table>
<tr id="test1" >
<td>
<button >Next</button>
</td>
</tr>
<tr id="test2" >
<td>
<button >Next</button>
</td>
</tr>
</table>
<div id="test3" >
</div>
</container>
JS:
$(".next").click(function() {
console.log($(this).parent().closest(".findMe").next().attr('id'));
})
I can find the ID "test2" but not "test3". Why?
CodePudding user response:
The second .findMe
's nearest ancestor with the third .findMe
is a grandparent, not a parent. (The <tr>
is inside a <tbody>
.)
While you could fix it (kinda) by making your dynamic DOM navigation more flexible, an easier method I think would be to select all .findMe
s, then access the next index.
const findMes = $('.findMe');
const thisIndex = findMes.index(this);
console.log(findMes[thisIndex 1]?.id);
You could also use getElementsByClassName
, whose collection is live, instead of re-selecting all elements each time.