Selecting Text Nodes with jQuery
Selecting text nodes within an element can be a challenging task in jQuery. Fortunately, there are various approaches available to achieve this.
Approach 1: Combining Contents() and Find()
jQuery doesn't provide a dedicated function for selecting text nodes. However, a workaround involves utilizing the contents() method, which retrieves child nodes including text nodes, and combining it with the find() method, which selects descendant elements but excludes text nodes.
var getTextNodesIn = function(el) { return $(el).find(":not(iframe)").addBack().contents().filter(function() { return this.nodeType == 3; }); };
Note: For jQuery versions prior to 1.7, replace addBack() with andSelf(), and for versions 1.8 or later, use addBack().
Approach 2: Pure DOM Solution
If you prefer a more efficient solution, a non-jQuery method can be employed. This involves a recursive function that traverses the DOM tree:
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; }
Example Usage
Both approaches allow you to retrieve all text nodes within a specified element.
var textNodes = getTextNodesIn(el);
By customizing the includeWhitespaceNodes parameter, you can choose whether or not whitespace text nodes are included in the result.
The above is the detailed content of How Can I Efficiently Select Text Nodes within an Element Using jQuery or Pure JavaScript?. For more information, please follow other related articles on the PHP Chinese website!