JQuery.parent () select multiple levels up

I have a hierarchy like this:

<search> <inner> <input/> <p/> <img/> </inner> </search> 

What I'm trying to do is select the parent <search> <input/> onFocus, but if I do this:

 $(function(){ $("input").focus(function(){ console.log($(this).parent("search")); }); }); 

The console shows an empty array. Is there a clean way to choose a parent of more than one level? The only way I know to do this is .parent().parent("search") , which will work, but not very clean, and if I were trying to select the parent 5 tiers, it would be just awful.

+7
jquery parent
source share
2 answers

Try .closest() :

For each element in the set, get the first element that matches the selector by testing the element itself and passing through its ancestors in the DOM tree.

 $(this).closest("search") 
+19
source share

From the docs :

The .parents () and .parent () methods are similar, except that the latter moves only one level up the DOM tree.

Try using $.parents .

+3
source share

All Articles