jQuery - 在兄弟中移动元素

时间:2016-07-28 19:48:52

标签: javascript jquery

我想将一个元素移动到兄弟姐妹。

我在下面的示例中,我想将所有.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 个答案:

答案 0 :(得分:2)

你的语法有些混乱。只需附加它,它就会移动

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

&#13;
&#13;
  $('.come-to-me').append(function() {
    return $(this).siblings('.i-want-to-be-your-child');
  });
&#13;
<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>
&#13;
&#13;
&#13;