score:4

Accepted answer

this refers to a plain DOM node element that doesn't implement neither an html() nor a text() method. Using $(this), you can make the element into a jQuery collection in order to be able to access the jQuery methods. Then you can use replaceWith() to replace the plain text nodes with the <div>s.

$('div').contents().filter(function()
{
    return this.nodeType === 3;
}).each(function()
{
    $(this).replaceWith("<div>" + $(this).text() + "</div>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
    aaaa
    <span>bbbb</span>
    cccc
    <span>dddd</span>
    eeee
</div>

score:1

You can also use wrap from jquery to wrap the content with div

.wrap()

Description: Wrap an HTML structure around each element in the set of matched elements.

REF: http://api.jquery.com/wrap/

$('div').contents().filter(function()
{
    return this.nodeType === 3;
}).each(function()
{
    $(this).wrap('<div>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
    aaaa
    <span>bbbb</span>
    cccc
    <span>dddd</span>
    eeee
</div>


Related Query

More Query from same tag