Javascript 查找 HTML 页面中的所有文本节点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10730309/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:41:32  来源:igfitidea点击:

Find all text nodes in HTML page

javascripthtml

提问by Phrogz

Possible Duplicate:
getElementsByTagName() equivalent for textNodes

可能的重复:
getElementsByTagName() 等效于 textNodes

For this questionI needed to find all text nodes under a particular node. I cando this like so:

对于这个问题,我需要找到特定节点下的所有文本节点。我可以这样做:

function textNodesUnder(root){
  var textNodes = [];
  addTextNodes(root);
  [].forEach.call(root.querySelectorAll('*'),addTextNodes);
  return textNodes;

  function addTextNodes(el){
    textNodes = textNodes.concat(
      [].filter.call(el.childNodes,function(k){
        return k.nodeType==Node.TEXT_NODE;
      })
    );
  }
}

However, this seems inelegant in light of the fact that with XPath one could simply query for .//text()and be done with it.

然而,鉴于使用 XPath 可以简单地查询.//text()并完成它这一事实,这似乎不雅。

What's the simplest way to get all text nodes under a particular element in an HTML document, that works on IE9+, Safari5+, Chrome19+, Firefox12+, Opera11+?

在 IE9+、Safari5+、Chrome19+、Firefox12+、Opera11+ 上获取 HTML 文档中特定元素下所有文本节点的最简单方法是什么?

"Simplest" is defined loosely as "efficient and short, without golfing".

“最简单”被粗略地定义为“高效且简短,无需打高尔夫球”。

回答by Phrogz

Based on @kennebec's answer, a slightly tighter implementation of the same logic:

基于@kennebec 的回答,对相同逻辑的一个稍微更严格的实现:

function textNodesUnder(node){
  var all = [];
  for (node=node.firstChild;node;node=node.nextSibling){
    if (node.nodeType==3) all.push(node);
    else all = all.concat(textNodesUnder(node));
  }
  return all;
}

However, far faster, tighter, and more elegant is using createTreeWalkerso that the browser filters out everything but the text nodes for you:

然而,使用更快、更紧凑、更优雅的方式createTreeWalker,浏览器会为您过滤除文本节点之外的所有内容:

function textNodesUnder(el){
  var n, a=[], walk=document.createTreeWalker(el,NodeFilter.SHOW_TEXT,null,false);
  while(n=walk.nextNode()) a.push(n);
  return a;
}

回答by kennebec

function deepText(node){
    var A= [];
    if(node){
        node= node.firstChild;
        while(node!= null){
            if(node.nodeType== 3) A[A.length]=node;
            else A= A.concat(deepText(node));
            node= node.nextSibling;
        }
    }
    return A;
}