【问题标题】:How to move an element into the next parent element in the DOM?如何将元素移动到 DOM 中的下一个父元素?
【发布时间】:2021-04-13 03:45:47
【问题描述】:

我正在努力将一个元素移动到 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");

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

【问题讨论】:

  • 就像香草JS方式的附录:document.querySelectorAll(".tmb").forEach(t =&gt; t.append(t.previousElementSibling))

标签: jquery dom insertafter


【解决方案1】:

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

$('p').each((i, p) =&gt; $(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>

或者,您可以循环遍历前面有pinsertAfter() 的所有.tmb 元素,其中包含.price

$('p + .tmb').each((i, t) =&gt; $(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>

【讨论】:

  • 这很完美,正是我所需要的。谢谢!
  • 由于.tmb 中除了.price 之外没有其他元素,您可以只使用$(t).prev(".p").appendTo(t) 而不是.insertAfter(...) + .find()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-07-20
  • 2011-02-05
  • 2010-11-19
  • 2017-12-17
  • 1970-01-01
  • 2014-01-21
  • 1970-01-01
相关资源
最近更新 更多