Home >Web Front-end >JS Tutorial >How Can I Efficiently Retrieve All Descendant Text Nodes of an Element Using jQuery or a Non-jQuery Approach?

How Can I Efficiently Retrieve All Descendant Text Nodes of an Element Using jQuery or a Non-jQuery Approach?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-17 19:41:11881browse

How Can I Efficiently Retrieve All Descendant Text Nodes of an Element Using jQuery or a Non-jQuery Approach?

Retrieving Text Nodes with jQuery

The task of retrieving all descendant text nodes of an element as a jQuery collection can pose a challenge. While jQuery lacks a dedicated function for this specific purpose, we can achieve this objective by combining the functionalities of contents() and find().

jQuery Approach:

var getTextNodesIn = function(el) {
    return $(el).find(":not(iframe)").addBack().contents().filter(function() {
        return this.nodeType == 3;
    });
};

getTextNodesIn(el);

This approach retrieves all descendant text nodes, excluding iframes.

Non-jQuery Approach:

For a more efficient solution, a recursive DOM-based function can be employed:

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);

This function can handle non-jQuery elements, providing greater control over whitespace text node inclusion.

The above is the detailed content of How Can I Efficiently Retrieve All Descendant Text Nodes of an Element Using jQuery or a Non-jQuery Approach?. 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