首页 > 解决方案 > 如何将元素移动到 DOM 中的下一个父元素?

问题描述

我正在努力将一个元素移动到 DOM 中的下一个元素中。我可以移动它,但它会不断重复到具有相同类的其他 div 中。

这是我的 HTML:

    <p>The first text that needs to be moved</p>
    <div class="tmb">
      <span class="price">500</span>
    </div>
    <p>Second text that needs to be moved</p>
    <div class="tmb">
      <span class="price">500</span>
    </div>

我想要发生的是第一个p元素将插入第一个.price元素之后。第二个p元素将插入到第二个.price元素之后。我不能给p元素一个类,因为它们是动态创建的。

我有这个 jQuery:

   $(".tmb").prev("p").insertAfter("span.price");

但这p在每个.price元素之后移动元素,这是合乎逻辑的。我只是希望它.price在 DOM 中遇到的第一个元素之后移动。

标签: jquerydominsertafter

解决方案


要实现这一点,您可以遍历所有p元素,因为有多个,然后使用appendTo()将它们添加到它们的相关.tmb. 尝试这个:

$('p').each((i, p) => $(p).appendTo($(p).next('.tmb')));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>The first text that needs to be moved</p>
<div class="tmb">
  <span class="price">500</span>
</div>
<p>Second text that needs to be moved</p>
<div class="tmb">
  <span class="price">500</span>
</div>

或者,您可以遍历所有.tmb以 a 开头的元素以及其中p包含insertAfter()的元素.price

$('p + .tmb').each((i, t) => $(t).prev('p').insertAfter($(t).find('.price')));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>The first text that needs to be moved</p>
<div class="tmb">
  <span class="price">500</span>
</div>
<p>Second text that needs to be moved</p>
<div class="tmb">
  <span class="price">500</span>
</div>


推荐阅读