Selecting Text Nodes with jQuery
Selecting descendant text nodes of an element with jQuery requires a bit of creativity. While jQuery does not offer a specific function for this task, it's possible to combine the methods contents() and find() to achieve the desired result.
jQuery Solution
var getTextNodesIn = function(el) { return $(el).find(":not(iframe)").addBack().contents().filter(function() { return this.nodeType == 3; }); }; getTextNodesIn(el);
This code gathers child nodes, including text nodes, using contents(). It then isolates descendant elements and text nodes using find(). Note that this solution requires special handling for iframe elements.
Pure JavaScript Solution
If you prefer a pure JavaScript approach, the following function can be used:
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; iThis function recursively traverses the DOM tree, identifying text nodes based on their node type. It allows the inclusion of whitespace nodes by passing a parameter.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3