JSFiddle - React, Tailwind, and code Playground
by jfriend00
HTML
<div>
<div>
<p id="para1">Some Text</p>
</div>
</div>
<p id="para2">More Text</p>
JavaScript
function log(args) {
var str = "";
for (var i = 0; i < arguments.length; i++) {
if (typeof arguments[i] === "object") {
str += JSON.stringify(arguments[i]);
} else {
str += arguments[i];
}
}
var div = document.createElement("div");
div.innerHTML = str;
document.body.appendChild(div);
}
function getLeafNodes(master) {
var results = [];
var children = master.childNodes;
for (var i = 0; i < children.length; i++) {
if (children[i].nodeType == 1) {
var childLeafs = getLeafNodes(children[i]);
if (childLeafs.length) {
// if we had child leafs, then concat them onto our current results
results = results.concat(childLeafs);
} else {
// if we didn't have child leafs, then this must be a leaf
results.push(children[i]);
}
}
}
// if we didn't find any leaves at this level, then this must be a leaf
if (!results.length) {
results.push(master);
}
return results;
}
var leafNodes = getLeafNodes(document.body);
log("LeafNodes");
log("<hr>");
for (var i = 0; i < leafNodes.length; i++) {
log(leafNodes[i].tagName);
}