jQuery - wrap all unwrapped text in p tags

Solution 1:

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

Solution 2:

here you go: http://jsfiddle.net/RNt6A/

$('div').wrapInner('<p></p>');​​​​
$('div p > p').detach().insertAfter('div p');

Solution 3:

Try this :-

<div class="container">
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>​

JS

    $(function(){
    var $temp = $('<div>');
    $('div.container p').each(function(){
            $(this).appendTo($temp);            
    });     

    if($.trim( $('div.container').html() ).length){
       var $pTag = $('<p>').html($('.container').html()); 
        $('div.container').html($pTag);
    }

    $('div.container').append($temp.html());
});
​

​Here is the working example :-

http://jsfiddle.net/dhMSN/12