Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
441 views
in Technique[技术] by (71.8m points)

jquery - How to move an element into the next parent element in the DOM?

I'm struggling to move an element into the next element in the DOM. I can move it but it keeps repeating itself into the other div's with the same class.

This is my 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>

What I want to happen is that the first p element will be inserted after the first .price element. The second p element will be inserted after the second .price element. I can't give the p elements a class because they are created dynamically.

I have this jQuery:

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

But this moves the p element after every .price element, which is logically. I just want it to move after the first .price element that it comes across in the DOM.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To achieve this you could loop through all p elements as there are multiple, and then use appendTo() to add them to their related .tmb. Try this:

$('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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...