Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

nth parent of each filtered element in Jquery

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading