'How to use jQuery to query div elements that are not contained by any other div elements?
$('div') will find all the <div> elements.
However, I want to query such situation:
<div class="shoud_be_in_query">
<div> test </div>
</div>
<section>
<div class="shoud_be_in_query">
<div> test </div>
</div>
<div class="shoud_be_in_query">
<div> test </div>
</div>
</section>
<section>
<section>
<div class="shoud_be_in_query"> test </div>
</section>
</section>
I want to query out all the div that is not a children of any other div. Is there any way to do that?
Solution 1:[1]
You can use the .filter() like:
$("div").filter(function() {
return $(this).parent()[0].tagName !== "DIV"
})
Demo
console.log($("div").filter(function() {
return $(this).parent()[0].tagName !== "DIV"
}).length)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="shoud_be_in_query">
<div> test </div>
</div>
<section>
<div class="shoud_be_in_query">
<div> test </div>
</div>
<div class="shoud_be_in_query">
<div> test </div>
</div>
</section>
<section>
<section>
<div class="shoud_be_in_query"> test </div>
</section>
</section>
Solution 2:[2]
You can try this way to filter all elements having div parents out.
$('div').filter((index, element) => $(element).parent()[0].localName !== 'div')
Solution 3:[3]
Assuming:
I want to query out all the div that is not a child of any other div
You can use the selector
:not(div) > div
which you can use with jQuery, document.querySelectorAll or CSS (so no need for js depending on what you need it for)
Example:
console.log($("div").length)
console.log($(":not(div) > div").length)
console.log($(":not(div) > div").filter(".shoud_be_in_query").length == $(":not(div) > div").length)
console.log($(":not(div) > div").filter(":not(.shoud_be_in_query)").length == 0)
console.log(document.querySelectorAll(":not(div) > div").length)
:not(div)>div {
border: 1px solid red;
}
div {
border: 1px solid blue;
margin: 2px;
padding: 2px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="shoud_be_in_query">
<div> test </div>
</div>
<section>
<div class="shoud_be_in_query">
<div> test </div>
</div>
<div class="shoud_be_in_query">
<div> test </div>
</div>
</section>
<section>
<section>
<div class="shoud_be_in_query"> test </div>
</section>
</section>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Nick Vu |
| Solution 3 | freedomn-m |
