Home > other >  How to use jQuery to query div elements that are not contained by any other div elements?
How to use jQuery to query div elements that are not contained by any other div elements?

Time:03-04

$('div') will find all the <div> elements.

However, I want to query such situation:

<div >
  <div> test </div>
</div>
<section>
  <div >
      <div> test </div>
  </div>
  <div >
      <div> test </div>
  </div>
</section>
<section>
  <section>
    <div > 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?

CodePudding user response:

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 >
  <div> test </div>
</div>
<section>
  <div >
    <div> test </div>
  </div>
  <div >
    <div> test </div>
  </div>
</section>
<section>
  <section>
    <div > test </div>
  </section>
</section>

CodePudding user response:

You can try this way to filter all elements having div parents out.

$('div').filter((index, element) => $(element).parent()[0].localName !== 'div')

CodePudding user response:

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 >
  <div> test </div>
</div>
<section>
  <div >
    <div> test </div>
  </div>
  <div >
    <div> test </div>
  </div>
</section>
<section>
  <section>
    <div > test </div>
  </section>
</section>

  • Related