简体   繁体   中英

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 .

  • 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>

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