Home > front end >  Insert each div inside next div (jQuery)
Insert each div inside next div (jQuery)

Time:06-11

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

What it is:

<div id="list">
 <div ></div>
 <div ></div>
 <div ></div>
 <div ></div>
 <div ></div>
 <div ></div>
</div>

What I want:

<div id="list">
  <div >
    <div ></div>
  </div>
  <div >
    <div ></div>
  </div>
  <div >
    <div ></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?

CodePudding user response:

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.

CodePudding user response:

This should do what you want:

$("#list .box.one").each(function (index) {
    $(this).prependTo($("#list .box.two")[index]);
});
  • Related