1

How to count top-level divs, which include 2 levels? For example,

<div>
   <div>
   </div>
   <div>
   </div>
</div>
<div>
   <div>
   </div>
   <div>
   </div>
</div>
<div>
   <div>
   </div>
   <div>
   </div>
</div>

Answer must be 3. Thanks for answer!

SalmanRote
  • 23
  • 5

4 Answers4

1

So I got all the children from the top level (document.body) then filtered the ones that are div elements and have 2 or more children.

const divs = [...document.body.children].filter(elm => elm.tagName == 'DIV' && elm.children.length > 1).length;

console.log(divs);
<div>
   <div>
   </div>
   <div>
   </div>
</div>
<div>
   <div>
   </div>
   <div>
   </div>
</div>
<div>
   <div>
   </div>
   <div>
   </div>
</div>
a.mola
  • 3,883
  • 7
  • 23
  • 2
    This is the best answer, but I want to point out that ANY answer to this question is going to be a bad practice. To the OP - if you want your `
    ` elements to be distinct in some way, you really, REALLY should add a class (or unique IDs) to those elements and select by that instead of working around W3C selector API with JavaScript.
    – rook218 Apr 06 '21 at 12:15
0

You're going to have a set a className attribute for all the top level div. So you should have something looking like this:

HTML

<div class="parentDiv">
   <div>
   </div>
   <div>
   </div>
</div>
<div class="parentDiv">
   <div>
   </div>
   <div>
   </div>
</div>
<div class="parentDiv">
   <div>
   </div>
   <div>
   </div>
</div>

JS

let x = document.querySelectorAll('.parentDiv');
console.log(x.length + 1);
samuelorobosa
  • 45
  • 1
  • 8
0

const allDivs = document.querySelectorAll('#range div');

// the "length" will give you the recurrent count for the query above.
console.log(allDivs.length)
<div id="range">
  <div>
    <div>
    </div>
    <div>
    </div>
  </div>
  <div>
    <div>
    </div>
    <div>
    </div>
  </div>
  <div>
    <div>
    </div>
    <div>
    </div>
  </div>
</div>
Rafael
  • 1
  • 3
0

Unfortunately, a "parent" selector still does not exist in CSS today, see here, but the following might help:

// get "top" level divs:
const topDivs = document.querySelectorAll('body > div');
console.log([...topDivs].map(d=>d.childNodes[0].textContent.trim()));

// get "divs having at least one further div as a child":
const twoLvlDivs=new Set()
document.querySelectorAll('div>div').forEach(d=>twoLvlDivs.add(d.parentNode));
console.log([...twoLvlDivs].map(d=>d.childNodes[0].textContent.trim()));
div {padding-left: 20px}
<div>1
  <div>1.1</div>
  <div>1.2</div>
</div>
<div>2
  <div>2.1</div>
  <div>2.2
    <div>2.2.1</div>
    <div>2.2.2</div>
  </div>
  <div>2.3</div>
</div>
<div>3
  <div>3.1</div>
  <div>3.2</div>
</div>
Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43