Domanda

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.

È stato utile?

Soluzione

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

Altri suggerimenti

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top