CKDT
CKDT

Reputation: 97

Find odd and even divs and put in containing div

I'm trying to solve something that should be really simple. But it's actually a bit trickier then I thought. I'm creating a Tumblr theme and I have a list with all posts in a containing div. For my layout I need two separate divs with all even and odd posts. How can I achieve such a thing with basic jquery?

<!-- Original -->
<div id="posts">
    <div class="post">Content odd</div>
    <div class="post">Content even</div>
    <div class="post">Content odd</div>
    <div class="post">Content even</div>
    <div class="post">Content odd</div>
    <div class="post">Content even</div>
</div>

<!-- New Situation -->
<div id="posts">
    <!-- Odd Posts -->
    <div id="col-one">
        <div class="post">Content odd</div>
        <div class="post">Content odd</div>
        <div class="post">Content odd</div>
    </div>
    <!-- Even Posts -->
    <div id="col-two">
        <div class="post">Content even</div>
        <div class="post">Content even</div>
        <div class="post">Content even</div>
    </div>
</div>

I found this fiddle http://jsfiddle.net/nick_craver/vmdaM/ which seems to almost be the solution but it isn't

Upvotes: 2

Views: 858

Answers (3)

Chandan Sarma
Chandan Sarma

Reputation: 308

Plz check this

<script>
            $(document).ready(function (){
                var even=$('div div:even');
               even.wrapAll('<div class="col-1" ><div>')
            });

        </script>

Upvotes: 0

rsnorman15
rsnorman15

Reputation: 510

Luckily jQuery makes this fairly easy but it considers the first element to be even since it has an index of 0. With that assumption it can be written like so:

var $oddPosts = $('.post:odd');
var $evenPosts = $('.post:even');

$oddPosts.wrapAll('<div class="col-one"></div>');
$evenPosts.wrapAll('<div class="col-two"></div>');

Here is a plunker showing it working and with the correct odd, even divs labeled: http://plnkr.co/edit/q7vH3RhwqJFCjTuQhJWi?p=preview

As pointed out, this will cause the even posts to appear before the odd posts since the jQuery wrapAll inserts the wrapper at the first element. To remedy this it requires just a bit more work:

var $oddPosts = $('.post:odd');
var $evenPosts = $('.post:even');

var $oddPostsCol = $('<div class="col-1"></div>').append($oddPosts);
var $evenPostsCol = $('<div class="col-2"></div>').append($evenPosts);

$('#posts').append($oddPostsCol).append($evenPostsCol);

http://plnkr.co/edit/kbXkqWNzWPZXAGBWBBrB?p=preview

Upvotes: 4

Jon Edwards
Jon Edwards

Reputation: 175

It sounds like this is what you're looking for:

oddDivs = $('div > div:nth-child(odd)');
evenDivs = $('div > div:nth-child(even)');
$('#col-one').append(oddDivs);
$('#col-two').append(evenDivs);

Upvotes: 0

Related Questions