Reputation: 458
I need to place a wrapper around all modules past the 2nd module.
<div class="show">
<div class="module">some content</div>
<div class="module">some content</div>
<div class="module">some content</div>
<div class="module">some content</div>
</div>
What I need is
<div class="show">
<div class="module">some content</div>
<div class="module">some content</div>
<h4 class="more">View More</h4>
<div class="show-more">
<div class="module">some content</div>
<div class="module">some content</div>
</div>
</div>
I can count the number of modules but I'm not sure how to append/prepend the html to the divs beyond the 1 index.
$('.show').each(function(i) {
var n = $(this).children('.module').length;
});
I should mention that I multiple "show" divs that each need have their own modules. So it needs to happen on each "show" div seperately. A loop maybe?
Upvotes: 0
Views: 24
Reputation: 21881
$(".show").each(function() {
$(".module:gt(1)", this)
.wrapAll('<div class="show-more" />')
.first()
.parent()
.before('<h4 class="more">View More</h4>');
});
Upvotes: 0
Reputation: 33870
Use .slice
:
$('.module').slice(2).wrapAll('<div class="show-more" />');
$('.show-more').before('<h4> Show more </h4>')
Multiple module :
$('.show').each(function(){
$(this).find('.module').slice(2).wrapAll('<div class="show-more" />')
.parent().before('<h4> Show more </h4>');
})
Upvotes: 1
Reputation: 1496
You want to use the jQuery wrapAll()
method, in conjunction with the :gt()
selector.
The :gt()
selector selects elements greater than a certain index, in your case 1
(0 based counting)
JSFiddle example.
UPDATED to include new information about separate .show
divs:
See code below:
$(".show").each(function (i, v) {
$(v).children(":gt(1)").wrapAll("<div class='showMore'/>");
});
Upvotes: 0