Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .parent() select multiple levels up

Tags:

jquery

parent

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.

like image 278
Liftoff Avatar asked Apr 09 '14 22:04

Liftoff


1 Answers

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")
like image 93
Oriol Avatar answered Oct 03 '22 23:10

Oriol