Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - wrap all unwrapped text in p tags

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

<div>
    Some text here which is not wrapped in tags
    <p>Some more text which is fine</p>
    <p>Blah blah another good line</p>
</div>

In this case it always seems to be the first line which is not being wrapped in p tags which might make the solution to this easier, although it's not every time. Some times it is fine.

What I need to do is identify whether the first line is wrapped or not and if not then wrap it.

Unfortunately I'm not sure where to start with this problem so any help would be appreciated.

like image 843
Tom Avatar asked Dec 12 '12 09:12

Tom


1 Answers

Try using this code to wrap any TextNodes that are not wrapped with <p> 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("<p>");
        }
    }​

here is a jsfiddle that shows this in action.

PS: TextNode detection part has been borrowed from this answer

like image 105
Arash Milani Avatar answered Oct 08 '22 19:10

Arash Milani