简体   繁体   中英

Append Child Elements to a Child Element in the same parent

How do you append child elements to a sibling using jQuery?

html

<div class="parent">
  <div class="child one">...</div>
  <div class="child">...</div>
  <div class="child">...</div>
</div>
<div class="parent">
  <div class="child one">...</div>
  <div class="child">...</div>
  <div class="child">...</div>
</div>

Script

$('.child').each(function(i, obj){
  if(!$(obj).hasClass('one')){
    $(obj).appendTo( .. Stuck here .. '.one');
  }
});

I can get the parent object but the trouble is then selecting the child with class 'one'.

Essentially I want to move all siblings so that the become children of the first child.

<div class="parent">
  <div class="child one">
    <div class="child">...</div>
    <div class="child">...</div>
  </div>
</div>
<div class="parent">
  <div class="child one">
    <div class="child">...</div>
    <div class="child">...</div>
  </div>
</div>

You want to append all the child not one into child one ?

$('.child').not('.one').appendTo('.one');

THE WORKING DEMO.

Get each element with class one , then append its siblings with class child .

$('.child.one').each(function(i, obj){
  $(obj).siblings('.child').each(function(j, child){
    $(child).appendTo(obj);
  });
});

Working Demo

Note: if you want the child elements outside the one element, replace appendTo with after .

try this:

$('.child').each(function(){
 if(!$(this).hasClass('one')){
  $(this).appendTo('.one');
}});

Working Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM