jQuery - 移动一个元素到其兄弟元素内部

3

我想将一个元素移动到其兄弟元素内。

在下面的示例中,我希望将所有的.i-want-to-be-your-child元素都移动到同一级别的兄弟元素.come-to-me内。


原始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>


我希望最终结果是

<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'));
});

我做错了什么?实现这个的最佳方法是什么? 这里是jsfiddle链接
1个回答

3
您的语法有些混乱。只需附加它,它就会移动。
$('.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>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接