Pregunta

With the following html

<ul id="accordion">
    <li>
        <ul>
            <li><h3>title</h3></li>
        </ul>
    </li>
    <li>
        <ul>
            <li><h3>title</h3></li>
        </ul>
    </li>
    <li>
        <ul>
            <li><h3>title</h3></li>
        </ul>
    </li>       
</ul>

I have the outer ul stored in a variable

var acc = $("#accordion")[0]  

in the general case I am just passed the DOM element and can't necessarily specify a selector

When a h3 is clicked I want to get the top level li that contains it. In the general case there could be any kind of markup between the accordion ul and the element I wnat to fetch, and between the element to fetch and the h3... but what I will have is a selector that lets me get to the element from the accordion using the ">" selector.

e.g. var items = $(">li", acc);

The trouble is that when I start from a clicked h3 ("this" inside the click handler) It's difficult to find the specific item.

$(this).closest(">li", acc);

returns an empty jQuery (maybe a bug? although it's difficult to define what ">" means in this instance, where the top level element is dynamic)

$(this).parents(">li")

doesn't allow a context to be set, so could potentially return too many elements

Is there a way to do what I want?

*edit: html now makes the problem clearer

¿Fue útil?

Solución 3

$(">li",acc).has(this)

works in general; setting a context on an initial jQuery appears to be the only place that startinga selector with ">" works in jQuery

Otros consejos

How about $(h3).closest(".item"); ? According to "closest" documentation, it will traverse the DOM up from current node until it finds a node that matches your selector.

Go the other way, to guarantee the child relationship:

acc.children('li').has(this);
jQuery(this).parents('li:last');
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top