"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > 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?

Posted on 2025-03-24
Browse:884

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 

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.

Latest tutorial More>

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