function countChars(elm) {
if (elm.nodeType == 3) { // TEXT_NODE
return elm.nodeValue.length;
}
var count = 0;
for (var i = 0, child; child = elm.childNodes[i]; i++) {
count += countChars(child);
}
return count;
}
I tried passing this function a string like countChars("hello"); but that didn't work. What are examples of elements that I can pass?
It expects a reference to a DOM node. That could be a text node (nodeType == 3) or an element node (nodeType == 1) by the look of the function. For example:
countChars(document.getElementById("someId"));
The following HTML would cause the above call to return 5:
<span id="someId">Hello</span>
If the argument is a text node the function returns the number of characters that make up that node. If the argument is an element node the function recursively counts the number of characters that make up the descendant text nodes of the element.
The following HTML would cause the above call to return 10 (the child node is included):
<div id="someId">Outer<span>inner</span></div>
You can see the full list of node types on MDN.
It expects DOM nodes, like something you'd get from document.getElementById() or the list of child nodes on another DOM node.
What it does is find all the text nodes in the list of child nodes of an element and count up how many characters they contain. It does it recursively, so it will find all the text within a container, no matter how far separated in the element graph.
Also it should be noted that this code expects a node to be either a text node or else an element. There are other types of nodes, however, most notably comment nodes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With