70

For this question I needed to find all text nodes under a particular node. I can do 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.

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

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

3
  • 1
  • Aw, bugger. Thanks, Jack, I did search but failed to find that question.
    – Phrogz
    May 24, 2012 at 3:13
  • Yeah, I don't know why it didn't show up in the side bar either, but I found it while doing a Google search :)
    – Ja͢ck
    May 24, 2012 at 3:26

2 Answers 2

195

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

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 createTreeWalker so that the browser filters out everything but the text nodes for you:

function textNodesUnder(el){
  var n, a=[], walk=document.createTreeWalker(el,NodeFilter.SHOW_TEXT,null,false);
  while(n=walk.nextNode()) a.push(n);
  return a;
}
7
  • 13
    @julmot On my computer, looking for all text nodes on this page using Chrome v50, it takes 1900μs using the first technique, but 220μs using the TreeWalker technique. So, 8 or 9 times faster.
    – Phrogz
    Apr 19, 2016 at 14:59
  • 3
    I had to tweek this in order to exclude the contents of <script> elements: gist.github.com/Daniel-Hug/1415b4d027e3e9854456f4e812ea2ce1 Sep 5, 2016 at 0:50
  • 1
    If you're using the TreeWalker method and you want to exclude script or style tags as Web_Designer mentioned, you can pass a filter as the third argument to createTreeWalker
    – Vinay Pai
    Jul 26, 2017 at 20:44
  • 1
    @VinayPai - Caveat: the filter is only run on a node that has passed the whatToShow check, so in this case you couldn't use the convenient NodeFilter.SHOW_TEXT, but instead you'd have to add additional logic to manually filter text nodes by nodeType or something.
    – Sphinxxx
    Sep 11, 2018 at 17:20
  • 2
    @Web_Designer - Alternative while still using document.createTreeWalker(): gist.github.com/Sphinxxxx/ed372d176c5c2c1fd9ea1d8d6801989b
    – Sphinxxx
    Sep 11, 2018 at 18:09
6
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;
}
4
  • 1
    How about while (node) without the != null?
    – Phrogz
    May 24, 2012 at 2:33
  • 3
    Or even for (node=node.firstChild;node;node=node.nextSibling){ … }
    – Phrogz
    May 24, 2012 at 2:43
  • 1
    I was worried that the recursive solution might run into stack limit issues, but I see now that this is unlikely.
    – Phrogz
    May 24, 2012 at 2:46
  • 1
    Once you know the first (parent) node is a child node the only possible values for node.nextSibling are another child node or null.
    – kennebec
    May 24, 2012 at 3:55

Not the answer you're looking for? Browse other questions tagged or ask your own question.