Title 1

<" />

Title 1

<" />

Title 1

<"/>

Jquery - Wrap multiple tag child class inside new div

41 Views Asked by At

I want to wrap multiple class inside tag to a new div using jQuery, here is the case html:

<div class="article">
    <div>
        <h1>Title 1</h1>
    </div>
    <div>
        <img>
    </div>
    <div>
        <h1>Title 2</h1>
    </div>
    <div>
        <img>
    </div>
    <div>
        <h1>Title 3</h1>
    </div>
    <div>
        <img>
    </div>
</div>

Result :

<div class="article">
    <div class="img-div">
        <div>
            <h1>Title 1</h1>
        </div>
        <div>
            <img>
        </div>
    </div>
    <div class="img-div">
        <div>
            <h1>Title 2</h1>
        </div>
        <div>
            <img>
        </div>
    </div>
    <div class="img-div">
        <div>
            <h1>Title 3</h1>
        </div>
        <div>
            <img>
        </div>
    </div>
</div>

here is my attempt jQuery code:

$(".article").children("div h1, div img).wrap("<div class='img-div'"></div>);

I'm using jQuery wrap(); wrapAll(); but I just can't get the same result.

1

There are 1 best solutions below

0
SKJ On

If your markup has always the exact same order, you can do a loop like this:

var $set = $('.article').children();    
for(var i=0, len = $set.length; i < len; i+=2){
    $set.slice(i, i+2).wrapAll('<div class="img-div">');
}  
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<div class="article">
    <div>
        <h1>Title 1</h1>
    </div>
    <div>
        <img>
    </div>
    <div>
        <h1>Title 2</h1>
    </div>
    <div>
        <img>
    </div>
    <div>
        <h1>Title 3</h1>
    </div>
    <div>
        <img>
    </div>
</div>