graphic_dev graphic_dev - 4 months ago 30
jQuery Question

jQuery - Move element inside a sibling

I want to move an element to a sibling.

I the example below, I want to move all

.i-want-to-be-your-child
elements to be inside the sibling
.come-to-me
.



Original HTML

<div>
<a href="#" class="come-to-me">Welcome!</a>
<span class="i-want-to-be-your-child">Thank you!</span>
</div>

<div>
<a href="#" class="come-to-me">Welcome!</a>
<span class="i-want-to-be-your-child">Thank you!</span>
</div>




I want the end result to be

<div>
<a href="#" class="come-to-me">Welcome!<span class="i-want-to-be-your-child">Thank you!</span></a>
</div>

<div>
<a href="#" class="come-to-me">Welcome!<span class="i-want-to-be-your-child">Thank you!</span></a>
</div>




jQuery

$(document).ready(function() {
$('.i-want-to-be-your-child').detach().appendTo($(sibling('.come-to-me')));
//$('.i-want-to-be-your-child').appendTo($(this).parent().child('.come-to-me'));
});


What am I doing wrong? What is the best way to achieve this?

jsfiddle

Answer

You have the syntax somewhat mixed up. Just append it, and it will move

$('.come-to-me').append(function() {
    return $(this).siblings('.i-want-to-be-your-child');
});

  $('.come-to-me').append(function() {
    return $(this).siblings('.i-want-to-be-your-child');
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <a href="#" class="come-to-me">Welcome!</a>
  <span class="i-want-to-be-your-child">Thank you!</span>
</div>

<div>
  <a href="#" class="come-to-me">Welcome!</a>
  <span class="i-want-to-be-your-child">Thank you!</span>
</div>