David Tran
David Tran

Reputation: 10606

jquery select parent that has children with certain attributes

I've read this SO question :

jQuery - select children which has specific styles

but my problem is a bit different.

I want to select PARENTS that their 1st-level children (not all descendants) have some certain styles. Something like this :

<ul id="BIG">
    <li>Home

        <ul id="SMALL">
            <li> 123 </li>
            <li name="foo"> 123 </li>
            <li> 123 </li>
        </ul>

    </li>
    <li>Articles</li>
    <li>Petitions</li>
    <li>Contact</li>
</ul>

And I want to catch the UL with id="SMALL". But my selector catch all 2 UL tags :

$('ul:has(li[name="foo"])')

Any suggestion ?

Upvotes: 3

Views: 5650

Answers (2)

jfrej
jfrej

Reputation: 4648

Try this:

$('li[name="foo"]').parent();

Demo here.

Please note, selecting DOM elements based on their attributes is slow. Try to limit the scope of the search if you can. For example:

$('#BIG').find('li[name="foo"]').parent();

Upvotes: 2

Use the child selector >, like this:

$('ul > li[name="foo"]').parent()

See working demo

Upvotes: 3

Related Questions