Home >Web Front-end >JS Tutorial >How Can I Select Text Nodes within an Element Using jQuery or Pure JavaScript?

How Can I Select Text Nodes within an Element Using jQuery or Pure JavaScript?

Linda Hamilton
Linda HamiltonOriginal
2024-12-28 01:59:09251browse

How Can I Select Text Nodes within an Element Using jQuery or Pure JavaScript?

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; i < len; ++i) {
                getTextNodes(node.childNodes[i]);
            }
        }
    }

    getTextNodes(node);
    return textNodes;
}

getTextNodesIn(el);

This 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.

The above is the detailed content of How Can I Select Text Nodes within an Element Using jQuery or Pure JavaScript?. 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