Matt.
Matt.

Reputation: 1304

Use detach() to place each element after every other element in other div

I'm having a little trouble writing a Javascript function that utilizes jquery detach() to move some elements to another div. My issue is that I would like to place each detached element in a specific place, after every other element in said div and I'm having a little trouble figuring out how to do this.

For example:

<div id="col-left">
 <li>Item One</li>
 <li>Item Three</li>
 <li>Item Five</li>
</div>

<div id="col-right">
 <li>Item Two</li>
 <li>Item Four</li>
 <li>Item Six</li>
</div>

Needs to become:

<div id="col-left">
 <li>Item One</li>
 <li>Item Two</li>
 <li>Item Three</li>
 <li>Item Four</li>
 <li>Item Five</li>
 <li>Item Six</li>
</div>

I've tried a couple things, including what's below, but it doesn't give expected results.

$("#col-right li").each(function() {
   $(this).detach().insertAfter("#col-left li:nth-child(2n)");
});

I know I need to target every other item in #col-left and insert $(this) after it but I'm not sure how to write that. Any help would be greatly appreciated!

Upvotes: 0

Views: 38

Answers (1)

Stryner
Stryner

Reputation: 7328

One solution is to store all the left <li>'s in a variable, and insert based on index:

var $originalLeft = $("#col-left li");
$("#col-right li").each(function(index, el) {
   $(this).insertAfter($originalLeft.eq(index));
});

Also note that .detach isn't necessary since .insertAfter will already do that.

Example Fiddle

Upvotes: 2

Related Questions