Home >Web Front-end >JS Tutorial >How Can I Efficiently Select All Text Nodes Within an Element Using jQuery?

How Can I Efficiently Select All Text Nodes Within an Element Using jQuery?

Susan Sarandon
Susan SarandonOriginal
2024-12-23 13:51:19617browse

How Can I Efficiently Select All Text Nodes Within an Element Using jQuery?

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:

  • This approach may be inefficient compared to pure DOM methods.
  • A workaround is necessary due to jQuery's overloading of the contents() function.
  • Non-jQuery solutions, such as the following, provide a more efficient alternative:
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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn