Issue
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".
Solution
Using createTreeWalker
is a very efficient way of querying multiple nodes from the DOM.
/**
* Retrieves an array of all text nodes under a given element.
*
* @param { Node } el - The element under which to search for text nodes.
* @returns { Node[] } An array of text nodes found under the given element.
*/
function textNodesUnder(el) {
const children = [] // Type: Node[]
const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT)
while(walker.nextNode()) {
children.push(walker.currentNode)
}
return children
}
Note: A much more complete answer with multiple examples can be found here: getElementsByTagName() equivalent for textNodes
Answered By - Phrogz
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.