jQuery - wrap all unwrapped text in p tags

前端 未结 5 474
醉梦人生
醉梦人生 2020-12-02 02:21

I have a situation where the following code is getting written to my page.

Some text here which is not wrapped in tags

Some mor

5条回答
  •  孤街浪徒
    2020-12-02 02:33

    Try using this code to wrap any TextNodes that are not wrapped with

    tag.

    function getTextNodesIn(node, includeWhitespaceNodes) {
        var textNodes = [], whitespace = /^\s*$/;
    
        function getTextNodes(node) {
            if (node.nodeType == 3) {
                if (includeWhitespaceNodes || !whitespace.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;
        }
    
        var textnodes = getTextNodesIn($("#demo")[0])​​​​;
        for(var i=0; i < textnodes.length; i++){
            if($(textnodes[i]).parent().is("#demo")){
                $(textnodes[i]).wrap("

    "); } }​

    here is a jsfiddle that shows this in action.

    PS: TextNode detection part has been borrowed from this answer

提交回复
热议问题