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

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

Patricia Arquette
Release: 2024-12-16 12:32:11
Original
746 people have browsed it

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

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;
    });
};
Copy after login

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;
}
Copy after login

Example Usage

Both approaches allow you to retrieve all text nodes within a specified element.

var textNodes = getTextNodesIn(el);
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template