Reputation:
My Html
<div class="loop">
<article>1<article>
<article>2<article>
<article>3<article>
<article>4<article>
<article>5<article>
<article>6<article>
</div>
My JS:
$('.loop').find('article').each(function (index, section) {
if ( index < 3) {
// code here
}
})
I have no idea how to solve this:
I want to iterate over these items and wrap item 1,2,3 with a div. Also item 4,5,6 and 7,8,9 (if there are more items)
My desired Html would be:
<div class="loop">
<div="newContainer">
<article>1<article>
<article>2<article>
<article>3<article>
</div>
<div="newContainer">
<article>4<article>
<article>5<article>
<article>6<article>
</div>
</div>
Upvotes: 0
Views: 346
Reputation: 1117
If you prefer a longer, but simpler to understand solution, you can do this.
$(document).ready(()=>{
let newDiv = $("<div>");
let generalId=1, ctrl=3;
let dv = $("<div>");
dv.attr("id", "new-container"+generalId);
let oldDiv=$(".loop");
oldDiv.find("article").each(function (index, article) {
ctrl--;
dv.append(article);
if(ctrl==0) {// if ctrl==0, we will append to new main div
newDiv.append(dv);
generalId++;
dv = $("<div>");
dv.attr("id", "new-container"+generalId);
ctrl=3;
}
});
if(ctrl>0) newDiv.append(dv);
oldDiv.html(newDiv.html());
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div class="loop">
<article>1</article>
<article>2</article>
<article>3</article>
<article>4</article>
<article>5</article>
<article>6</article>
<article>7</article>
</div>
</body>
</html>
Upvotes: 0
Reputation: 2333
Another way you could do this would be to also use wrapAll
inside of your each
.
var article = $('article');
$.each(article, function (index, section) {
if (index % 3 === 0) {
$(article).slice(index, index + 3).wrapAll("<div class='new-div'>Test text</div>");
};
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="loop">
<article>1</article>
<article>2</article>
<article>3</article>
<article>4</article>
<article>5</article>
<article>6</article>
</div>
Upvotes: 0
Reputation: 519
I write a solution for you:
$('.loop').find('article').each(function (index, section) {
if(index % 3 ===0)
{
$('.loop').append($('<div>'));
}
$('.loop').children(`div:nth-of-type(${Math.floor(index/3)+1})`).first().append(section);
})
here is a full example: https://jsfiddle.net/t40ujrbs/
Upvotes: 1