I have a bunch of divs inside a wrapper and want to wrap every 5 with a new parent. So markup starts like:
<div >
<div class=child"></div>
<div class=child"></div>
<div class=child"></div>
<div class=child"></div>
<div class=child"></div>
</div>
Then I have an ajax load more button which pulls in another 5 divs inside the "wrapper" div so markup looks like:
<div >
<div class=child"></div>
<div class=child"></div>
<div class=child"></div>
<div class=child"></div>
<div class=child"></div>
<div class=child"></div>
<div class=child"></div>
<div class=child"></div>
<div class=child"></div>
<div class=child"></div>
</div>
At this point - I want to wrap every 5 divs in a new parent so markup becomes:
<div >
<div >
<div class=child"></div>
<div class=child"></div>
<div class=child"></div>
<div class=child"></div>
<div class=child"></div>
</div>
<div >
<div class=child"></div>
<div class=child"></div>
<div class=child"></div>
<div class=child"></div>
<div class=child"></div>
</div>
</div>
Then if ajax load more button is clicked again, new child divs will get added to the parent "wrapper" which should again get wrapped inside the "newparent" div...
<div >
<div >
<div class=child"></div>
<div class=child"></div>
<div class=child"></div>
<div class=child"></div>
<div class=child"></div>
</div>
<div >
<div class=child"></div>
<div class=child"></div>
<div class=child"></div>
<div class=child"></div>
<div class=child"></div>
</div>
<div >
<div class=child"></div>
<div class=child"></div>
</div>
</div>
This works using my code below... BUT.. the code I am using wraps the "new parent" inside another version so I get unwanted nested divs... Any help suggestions on what I am not doing right here please?
var $span = $(".wrapper .child");
for (var i = 0; i < $span.length; i = 6) {
var $div = $("<div/>", {
class: 'newParent'
});
$span.slice(i, i 6).wrapAll($div);
}
I guess I need a statement to say only apply this logic to immediate children "child" divs in the parent "wrapper" div?
CodePudding user response:
Change $(".wrapper .child")
to $(".wrapper > .child")
.
This change will target only the .child
elements which have been appended directly to .wrapper
and have not already been wrapped after a previous AJAX request