Skip to content

Instantly share code, notes, and snippets.

@pseudosavant
Created April 20, 2015 22:04
Show Gist options
  • Save pseudosavant/de02f35b1641bee1246f to your computer and use it in GitHub Desktop.
Save pseudosavant/de02f35b1641bee1246f to your computer and use it in GitHub Desktop.
Find all decendent text and element nodes that don't have any children
// Find all decendent text and element nodes that don't have any children
function findChildless(currentNode) {
var nodes = [];
// Recursion
// If currentNode has children
if (currentNode.hasChildNodes()) {
// Run `findChildless` on all children
for (var i=0; i < currentNode.childNodes.length; i++) {
var results = findChildless(currentNode.childNodes[i]);
// If there are results, concat the results with `nodes` Array
if (results) {
nodes = nodes.concat(results);
}
}
} else { // No children
if (currentNode.nodeType === 1 || currentNode.nodeType === 3) {
// Push `currentNode` onto `nodes` Array if it is a text or element node type
nodes.push(currentNode);
}
}
// Return nodes list
return nodes;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment