【发布时间】: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 => t.append(t.previousElementSibling))
标签: jquery dom insertafter