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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
And now I want count how many <ul >
has child elements in this case it has only 1 li
.
CodePudding user response:
- Use
children
instead ofchildNodes
. 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>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>