-
-
Save my8bit/7143332 to your computer and use it in GitHub Desktop.
Get only text nodes inside dom element
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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