jbarradas jbarradas - 4 months ago 18
Javascript Question

jQuery - has children without ANY class (not specific class)

So, guys, basically what I need to find:

----> All

<li>
which has
<ul>
without ANY class.

In this example I would ONLY want the
<li>
parent of the commented
<ul>
:

HTML

<ul id="myList">
<li>
<a>Item 1</a>
<ul class="someClass">

</ul>
</li>
<li> <!--------- Just Need This One ---------->
<a>Item 2</a>
<ul>

</ul>
</li>
<li>
<a>Item 3</a>
<ul class="justAnotherClass">

</ul>
</li>
</ul>


I'm aware of
.not("[class]")
, and so I tried something like:

$('#myList li').has('ul').not("[class]")


which obviously doesn't work because jQuery is looking for
<li>
's which have a nested
<ul>
but doesn't have any class.

So, guys, can anyone please help? :)

Answer

Instead of using

$('#myList li').has('ul').not("[class]")

you can use

$('#myList > li').has('ul:not([class])')

you can also use this selector

$('#myList > li:has(ul:not([class]))')

$('#myList > li:has(ul:not([class]))').css('background' , 'red');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="myList">
    <li>
        <a>Item 1</a>
        <ul class="someClass">

        </ul>
    </li>
    <li>
        <a>Item 2</a>
        <ul>    <!--------- Just Need This One ---------->
        
        </ul>
    </li>
    <li>
        <a>Item 3</a>
        <ul class="justAnotherClass">
        
        </ul>
    </li>
</ul>