WordPress Mike
WordPress Mike

Reputation: 458

Wrap everything beyond 3rd div in another div

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

Answers (3)

Andreas
Andreas

Reputation: 21881

$(".show").each(function() {
    $(".module:gt(1)", this)
            .wrapAll('<div class="show-more" />')
            .first()
            .parent()
            .before('<h4 class="more">View More</h4>');
});

fiddle

Upvotes: 0

Karl-Andr&#233; Gagnon
Karl-Andr&#233; Gagnon

Reputation: 33870

Use .slice :

$('.module').slice(2).wrapAll('<div class="show-more" />');
$('.show-more').before('<h4> Show more </h4>')

http://jsfiddle.net/tBq5U/1/


Multiple module :

$('.show').each(function(){
    $(this).find('.module').slice(2).wrapAll('<div class="show-more" />')
    .parent().before('<h4> Show more </h4>');
})

http://jsfiddle.net/tBq5U/2/

Upvotes: 1

Soturi
Soturi

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

Related Questions