Skip to content
Advertisement

Insert each div inside next div (jQuery)

How can I insert div.one into his next div.two with jquery?

What it is:

<div id="list">
 <div class="box one"></div>
 <div class="box two"></div>
 <div class="box one"></div>
 <div class="box two"></div>
 <div class="box one"></div>
 <div class="box two"></div>
</div>

What I want:

<div id="list">
  <div class="box two">
    <div class="box one"></div>
  </div>
  <div class="box two">
    <div class="box one"></div>
  </div>
  <div class="box two">
    <div class="box one"></div>
  </div>
</div>

What I tried (but it insert all div.one in every div.two):

$("#list .box.one").each(function() {
    $(this).prependTo(".box.two").next();
});

Whats my fail?

Advertisement

Answer

You were close:

$("#list .box.one").each(function() {
    $(this).prependTo($(this).next());
});

using the class in the preprendTo() function will of course select all the .box.two elements, instead by doing $(this).next() we only get the very next sibling element.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement