Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 908
transbetacism Avatar asked Jul 26 '26 09:07

transbetacism


1 Answers

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>
like image 173
adeneo Avatar answered Jul 27 '26 22:07

adeneo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!