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

柔情痞子 提交于 2019-11-28 23:46:45

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(' ');
}
He Nrik

This is the simplest solution I could think of:

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!