编程语言
首页 > 编程语言> > 使用javascript递归计数文本节点

使用javascript递归计数文本节点

作者:互联网

假设我有这样的标记

<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>

我的js代码

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

现在,如果我想计算文本节点

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

这应该归还给我计数,但它不起作用,而且我应该把它放在其他条件下.
我从来没有使用过nodeType这样有问题使用它.任何帮助将不胜感激.

解决方法:

您的代码中存在一些错误:

>您的HTML格式不正确.
>您正在将文本附加到计数器而不是增加它.
>永远不会遍历节点的子节点,始终将同一节点传递给递归调用.
>如果节点不是文本节点,则不执行任何操作.

这将有效:

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

哪个数字对应于哪个节点类型can be found here.

更新:

如果要计算单词,则必须先将每个文本节点拆分为单词.在下面我假设单词用空格分隔:

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

更新2

我知道你想使用递归函数,但如果你只想计算单词,那么有一种更简单,更有效的方法:

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;
}

标签:javascript,textnode
来源: https://codeday.me/bug/20190610/1211121.html