简体   繁体   中英

jQuery select items which parents are not of a given class

how can select all nodes with class "myClass" whose parent nodes don't have class "myClass".

for example, i have 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 elements with ids "d1" and "d3"

actually, i'm trying to write a code that converts HTML from that example to a list with tabulations, such as:

d1
  d2
  d4
d3

(there can be more descedant nodes)

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

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

Or if you want to look beyond the direct parent:

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

This might work also:

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

A better solution for your exact example:

$(".myContainer > .myClass")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM