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

Time:11-27

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 >

<div >
    <div >
        <span>element</span>
    </div>
    <div >
        <span>element</span>
    </div>
</div>

<div >
    <div >
        <span>element</span>
    </div>
    <div >
        <span>element</span>
    </div>
</div>

my code

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

CodePudding user response:

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 >

  <div >
    <div >
      <span>element</span>
    </div>
    <div >
      <span>element</span>
    </div>
  </div>

  <div >
    <div >
      <span>element</span>
    </div>
    <div >
      <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 >

  <div >
    <div >
      <span>element</span>
    </div>
    <div >
      <span>element</span>
    </div>
  </div>

  <div >
    <div >
      <span>element</span>
    </div>
    <div >
      <span>element</span>
    </div>
  </div>

  • Related