Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

counting text node recursively using javascript

Let say I have a mark up like this

<html id="test">
<body>
Some text node.
<div class="cool"><span class="try">This is another text node.</span></div>
Yet another test node.
</body>
</html>

my js code

function countText(node){
 var counter = 0;
 if(node.nodeType === 3){
     counter+=node.nodeValue.length;
     countText(node);
 }
 else{}
}

Now if I want to count the text nodes

console.log("count text : " + countText(document.getElementById("test"));

this should return me the count but its not working and moreover what should I put in else condition. I never used nodeType so kind of having problem using it . Any help will be appreciated.

like image 710
user429035 Avatar asked Feb 24 '23 12:02

user429035


2 Answers

There are a couple of things wrong in your code:

  • Your HTML is malformed.
  • You are appending text to your counter instead of increasing it.
  • You never loop over the children of the a node, you always pass the same node to the recursive call.
  • You don't do anything if a node is not a text node.

This will work:

function countText(node){
    var counter = 0;
    if(node.nodeType === 3){
        counter++;
    }
    else if(node.nodeType === 1) { // if it is an element node, 
       var children = node.childNodes;    // examine the children
       for(var i = children.length; i--; ) {
          counter += countText(children[i]);
       }
    }
    return counter;  
}

alert(countText(document.body));

DEMO

Which number corresponds to which node type can be found here.


Update:

If you want to count the words, you have to split each text node into words first. In the following I assume that words are separated by white spaces:

if(node.nodeType === 3){
    counter = node.nodeValue.split(/\s+/g).length;
}

Update 2

I know you want to use a recursive function, but if you want to count the words only, then there is a much easier and more efficient way:

function countWords(node){
    // gets the text of the node and all its descendants
    var text = node.innerText || node.textContent
    return text.split(/\s+/g).length;
}
like image 145
Felix Kling Avatar answered Mar 13 '23 06:03

Felix Kling


You want something like

function countTextNodes(node) {
    var n = 0;
    if(node.nodeType == 3)
        n = 1;
    for(var i = 0; i < node.childNodes.length; ++i)
        n += countTextNodes(node.childNodes[i]);
    return n;
}

This can be compressed into more compact code, but I went for legibility here.

Call this on the root in which you want to count text nodes. For example, to count text nodes throughout the entire document, you would want to call countTextNodes(document.getDocumentElement()).

like image 21
kqnr Avatar answered Mar 13 '23 05:03

kqnr