Search code examples
jqueryappendinsertafter

jQuery - Moving one element after another element of it's parent


I want a code that moves the span in item-2 to after of span in item-1. I want this transition to happen in the parent element of each span, i.e. items-wrapper

<div class="wrapper">

<div class="items-wrapper">
    <div class="item-1">
        <span>element</span>
    </div>
    <div class="item-2">
        <span>element</span>
    </div>
</div>

<div class="items-wrapper">
    <div class="item-1">
        <span>element</span>
    </div>
    <div class="item-2">
        <span>element</span>
    </div>
</div>

my code

$(".item-2 span").each(function() {
    $(this).parent().insertAfter(".item-1 span");
});

Solution

  • Here you go. parent() goes only 1 step ahead so as per your requirement, $(this).parent().parent().find(".item-1"); to find actual dom to use insertAfter.

    Example:

    $(".item-2 span").each(function() {
      var elm = $(this).parent().parent().find(".item-1 span");
      $(this).insertAfter(elm);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="wrapper">
    
      <div class="items-wrapper">
        <div class="item-1">
          <span>element</span>
        </div>
        <div class="item-2">
          <span>element</span>
        </div>
      </div>
    
      <div class="items-wrapper">
        <div class="item-1">
          <span>element</span>
        </div>
        <div class="item-2">
          <span>element</span>
        </div>
      </div>

    Alternative using appendTo() which insert every element in the set of matched elements to the end of the target.

    Example:

    $(".item-2 span").each(function() {
      var elm = $(this).parent().parent().find(".item-1");
      $(this).appendTo(elm);
    
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="wrapper">
    
      <div class="items-wrapper">
        <div class="item-1">
          <span>element</span>
        </div>
        <div class="item-2">
          <span>element</span>
        </div>
      </div>
    
      <div class="items-wrapper">
        <div class="item-1">
          <span>element</span>
        </div>
        <div class="item-2">
          <span>element</span>
        </div>
      </div>