JQuery select elements whose parents are not of the given class

how to select all nodes with class "myClass", whose parent nodes do not have class "myClass".

for example I have the following HTML:

<div class="myContainer">
    <div class="myClass" id="d1"> 
        <div class="myClass" id="d2"></div>
        <div class="myClass" id="d4"></div>
    </div>
    <div class="myClass" id="d3"></div>
</div>

      

and I want to get a list of items with ids "d1" and "d3"

In fact, I'm trying to write code that converts the HTML from this example to a tabbed list, like this:

d1
  d2
  d4
d3

      

(there may be narrower knots)

+2


source to share


1 answer


I have come up with a number of possible solutions. May be:

$(":not(.myClass) > .myClass")

      

Or if you want to look beyond the direct parent:

$(":not(.myClass) .myClass")

      



This might work as well:

$(".myClass:has(:not(.myClass))")

      

Best solution for your exact example:

$(".myContainer > .myClass")

      

+7


source







All Articles