Selecting Text Nodes with jQuery
Retrieving all descendant text nodes of an element as a jQuery collection can be a complex task. Since jQuery lacks a dedicated function for this, a combination of methods is necessary.
The solution involves employing the contents() function, which retrieves child nodes (including text nodes), and the find() function, which selects all descendant elements (excluding text nodes). By merging these results, all text nodes within the specified element can be obtained.
var getTextNodesIn = function(el) { return $(el).find(":not(iframe)").addBack().contents().filter(function() { return this.nodeType == 3; }); }; getTextNodesIn(el);
Considerations:
function getTextNodesIn(node, includeWhitespaceNodes) { var textNodes = [], nonWhitespaceMatcher = /\S/; function getTextNodes(node) { if (node.nodeType == 3) { if (includeWhitespaceNodes || nonWhitespaceMatcher.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);
The above is the detailed content of How Can I Efficiently Select All Text Nodes Within an Element Using jQuery?. For more information, please follow other related articles on the PHP Chinese website!