Skip to content

Instantly share code, notes, and snippets.

@my8bit
Forked from IceCreamYou/Inc 500 TSV
Last active September 25, 2021 01:51
Show Gist options
  • Save my8bit/7143332 to your computer and use it in GitHub Desktop.
Save my8bit/7143332 to your computer and use it in GitHub Desktop.
Get only text nodes inside dom element
/**
* Get an array containing the text nodes within a DOM node.
*
* From http://stackoverflow.com/a/4399718/843621
*
* For example get all text nodes from <body>
*
* var body = document.getElementsByTagName('body')[0];
*
* getTextNodesIn(body);
*
* @param node Any DOM node.
* @param [includeWhitespaceNodes=false] Whether to include whitespace-only nodes.
* @return An array containing TextNodes.
*/
function getTextNodesIn(node, includeWhitespaceNodes) {
var textNodes = [], whitespace = /^\s*$/;
function getTextNodes(node) {
if (node.nodeType == 3) {
if (includeWhitespaceNodes || !whitespace.test(node.nodeValue)) {
textNodes.push(node);
}
} else {
for (var i = 0, len = node.childNodes.length; i < len; ++i) {
getTextNodes(node.childNodes[i]);
}
}
}
getTextNodes(node);
return textNodes;
}
getTextNodesIn(el);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment