Search code examples
jquerydominsertafter

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.


Solution

  • 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>

    Alternatively, you could loop through all the .tmb elements which are preceded by a p and insertAfter() the .price contained there.

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