Last active
March 23, 2021 00:46
-
-
Save pixelspencil/dd5b5fde3e4dc5a7211ad8d41a85c75e to your computer and use it in GitHub Desktop.
Script to count how many nodes are inside a parent element
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Function that runs and counts children inside a parent | |
function getCount(parent, getChildrensChildren){ | |
var relevantChildren = 0; | |
var children = parent.childNodes.length; | |
for(var i=0; i < children; i++){ | |
if(parent.childNodes[i].nodeType != 3){ | |
if(getChildrensChildren) | |
relevantChildren += getCount(parent.childNodes[i],true); | |
relevantChildren++; | |
} | |
} | |
return relevantChildren; | |
} | |
// template to use to check a selector and it's children | |
var element = document.querySelector("element"); | |
alert(getCount(element, false)); // Simply one level | |
alert(getCount(element, true)); // Get all child node count | |
// Example: check body dom nodes | |
var element = document.querySelector("body"); | |
alert(getCount(element, false)); // Simply one level | |
alert(getCount(element, true)); // Get all child node count | |
// Example: check parent class for it's children | |
var element = document.querySelector(".exampleclass"); | |
alert(getCount(element, false)); // Simply one level | |
alert(getCount(element, true)); // Get all child node count |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment