Search code examples
javascriptjqueryhtmlchildren

Wrap every immediate group of objects, including text, except divs inside a new div


I'm trying to wrap every immediate group of objects that is not a div inside a wrap class. Is there any way

Input:

var $code = 
'Lorem Ipsum
 <p>Foo Bar</p>
 <div class="myclass"></div>
 <p>Foo Bar</p>
 <div class="myclass"></div>'

var $object = $('<div/>').html($code);

Wanted output:

 <div class="wrap">
    Lorem Ipsum
    <p>Foo Bar</p>
 </div>
 <div class="myclass"></div>
 <div class="wrap">
    <p>Foo Bar</p>
 </div>
 <div class="myclass"></div>

What I've tried:

 $object.contents().not('> .myclass').wrap('<div class="wrap"></div>');

Can someone help me please? I'm stuck here.

Thank you very much!


Solution

  • Haven't checked whether there is a more optimal way to do it, but there you go

    var code =
        'Lorem Ipsum<p>Foo Bar</p><div class="myclass"></div><p>Foo Bar</p><div class="myclass"></div>'
    
    var $object = $('<div/>').html(code);
    
    var $obj = $();
    $object.contents().each(function () {
        if ($(this).hasClass('myclass')) {
            $obj.wrapAll('<div class="wrap"/>');
            $obj = $();
        } else {
            $obj = $obj.add(this)
        }
    })
    $obj.wrapAll('<div class="wrap"/>');
    

    Demo: Fiddle