Search code examples
jqueryparent

jQuery .parent() select multiple levels up


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.


Solution

  • 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")