JSFiddle - React, Tailwind, and code Playground
by jfriend00
HTML
<div id="result">Number of Elements = </div>
<div id="top">
<span>text </span>
<span><b><i>More Text</i></b></span>
<span>text </span>
<span>text </span>
<span>text </span>
</div>
CSS
#result {margin-bottom: 20px;}
JavaScript
function countDescendantElements(top) {
var node = top.firstChild;
var cnt = 0;
while (node && node != top) {
if (node.nodeType === 3) {
cnt++;
cnt += countDescendantElements(node);
}
node = node.nextSibling;
}
return(cnt);
}
document.getElementById("result").innerHTML += countDescendantElements(document.getElementById("top"));