I have a requirement where I need to find out 4th parent for each filtered item from jQuery.
$("a.dropdown-toggle").filter(function() {
return $(this).text().indexOf('ADD_DELET') > -1
}).parents().eq(4);
If the above filter function is returning single value , above code is working fine but if the filter function is returning more than one item. Above code is not working.
>Solution :
.eq(4) is selecting element 4 from all the parents of all selected dropdowns, not the 4th parent of each.
Use a .each() loop that adds the appropriate parent to a collection.
There’s also no need to use filter(), you can use the :contains() selector.
let parents = $([]); // empty collection
$("a.dropdown-toggle:contains(ADD_DELET)").each(function() {
parents = parents.add($(this).parents().eq(4));
});
It would be easier if you gave those parents a unique class, then you could use .closest():
let parents = $("a.dropdown-toggle:contains(ADD_DELET)").closest(".classname");
This is more robust than counting parents, since it won’t break if the organization is modified to add or remove nesting levels.