Using jQuery to gather all text nodes from a wrapped set, separated by spaces

后端 未结 3 2070
盖世英雄少女心
盖世英雄少女心 2020-12-15 11:37

I\'m looking for a way to gather all of the text in a jQuery wrapped set, but I need to create spaces between sibling nodes that have no text nodes between them.

For

相关标签:
3条回答
  • 2020-12-15 11:46

    jQuery deals mostly with elements, its text-node powers are relatively weak. You can get a list of all children with contents(), but you'd still have to walk it checking types, so that's really no different from just using plain DOM childNodes. There is no method to recursively get text nodes so you would have to write something yourself, eg. something like:

    function collectTextNodes(element, texts) {
        for (var child= element.firstChild; child!==null; child= child.nextSibling) {
            if (child.nodeType===3)
                texts.push(child);
            else if (child.nodeType===1)
                collectTextNodes(child, texts);
        }
    }
    function getTextWithSpaces(element) {
        var texts= [];
        collectTextNodes(element, texts);
        for (var i= texts.length; i-->0;)
            texts[i]= texts[i].data;
        return texts.join(' ');
    }
    
    0 讨论(0)
  • 2020-12-15 11:58

    This is the simplest solution I could think of:

    $("body").find("*").contents().filter(function(){return this.nodeType!==1;});
    
    0 讨论(0)
  • 2020-12-15 12:01

    You can use the jQuery contents() method to get all nodes (including text nodes), then filter down your set to only the text nodes.

    $("body").find("*").contents().filter(function(){return this.nodeType!==1;});
    

    From there you can create whatever structure you need.

    0 讨论(0)
提交回复
热议问题