zyyyzzz
zyyyzzz

Reputation: 230

Count parent child child nodes

So I want to know how do I get count of parent child child childs for example:

const parent = document.querySelectorAll('.parent');
parent.forEach(el => {
  const ul = el.querySelector('.child3-child');
  const div = document.createElement('div');
  div.textContent = ul.childNodes.length;
  el.append(div);
});
<div class="parent">
  <div class="child1">
   text
  </div>
  <div class="child2">
   text
  </div>
  <div class="child3">
    <ul class="child3-child">
     <li>
      some text...
     </li>
    <ul>
  </div>
</div>

And now I want count how many <ul class="child3-child"> has child elements in this case it has only 1 li.

Upvotes: 1

Views: 77

Answers (1)

I wrestled a bear once.
I wrestled a bear once.

Reputation: 23379

  • Use children instead of childNodes. The former includes HTML Elements while the latter includes text nodes.
  • Close your </ul> tag properly or else the borwser will think it's opening a nested element.

const parent = document.querySelectorAll('.parent');
parent.forEach(el => {
  const ul = el.querySelector('.child3-child');
  const div = document.createElement('div');
  div.textContent = ul.children.length;
  el.append(div);
});
<div class="parent">
  <div class="child1">
   text
  </div>
  <div class="child2">
   text
  </div>
  <div class="child3">
    <ul class="child3-child">
     <li>
      some text...
     </li>
    </ul> <!--- This wasn't properly closed -->
  </div>
</div>

Upvotes: 2

Related Questions