1

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> 

3 Answers 3

2

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

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

THE WORKING DEMO.

Sign up to request clarification or add additional context in comments.

1 Comment

This is almost what I am looking for only I can use appendTo('.one') because there will be multiple instances of parent with child 'one'
1

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.

Comments

0

try this:

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

Working Demo

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.