Reputation: 25392
I have a hierarchy like this:
<search>
<inner>
<input/>
<p/>
<img/>
</inner>
</search>
What I am trying to do is to select the parent <search>
of the <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 select a parent more than one level up? The only way I know of to do this would be .parent().parent("search")
, which would work, but is not very clean, and if I were trying to select a parent 5 tiers up, would be just atrocious.
Upvotes: 21
Views: 16589
Reputation: 19539
From the docs:
The .parents() and .parent() methods are similar, except that the latter only travels a single level up the DOM tree.
Try using $.parents
instead.
Upvotes: 4
Reputation: 288140
Try .closest()
:
For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.
$(this).closest("search")
Upvotes: 39