I have several div and I try to add more around all 3 elements with append in jQuery :
I have :
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
<div>9</div>
And I try to insert other div like that :
<div class="container-1">
<div>1</div>
<div>2</div>
<div>3</div>
</div>
<div class="container-2">
<div>4</div>
<div>5</div>
<div>6</div>
</div>
<div class="container-3">
<div>7</div>
<div>8</div>
<div>9</div>
</div>
I tried with append function but it no work, I don't know if is possible ? Then, I know I need a for loop for this. Thank you for your help.
You may loop over the existing div
s and append them to containers.
In the iteration, you can keep track of the current container. If the container's inner element's count exceeds 2, create a new container.
This goes on until all the div
s have been moved to containers.
var container, count = 0; $('div').each(function() { if (!container || container.find('div').length > 2) { container = $(`<div class="container-${++count}"></div>`).appendTo('body'); } $(this).appendTo(container); });
div[class^=container] { border: 1px dashed darkgray; padding: 5px; margin-bottom: 5px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div>1</div> <div>2</div> <div>3</div> <div>4</div> <div>5</div> <div>6</div> <div>7</div> <div>8</div> <div>9</div>
You can surround all those div
s with a container div
, say div
with id = 'container'
then you can loop over all the div
and then get the outerHTML
of each element and group each three div
in a separate div
.
var nHTML = '', finalHTML = '', i=1;; $('#container div').each(function(index, elem){ if(index == 0 || index % 3 !==0){ nHTML += elem.outerHTML; } else{ finalHTML += '<div class="container-'+i+'">'+nHTML+'</div>'; i++; nHTML = elem.outerHTML; } }); $('#container').html(finalHTML);
.container-1{ color: green; } .container-2{ color: red; } .container-3{ color: blue; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id='container'> <div>1</div> <div>2</div> <div>3</div> <div>4</div> <div>5</div> <div>6</div> <div>7</div> <div>8</div> <div>9</div> <div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.