Tom Harris Tom Harris - 2 months ago 13
jQuery Question

Move multiple elements position relative to another element with jQuery

I have multiple of the following elements:

<div class="item">
<div class="image">Image</div>
<div class="text">Text</div>
</div>


And what I need to do in jQuery is to swap them around, so that the text div is displayed before the image div.

This works fine using $('.text')insertBefore('.image') - but this doesn't work when I have multiple item divs.

They all need to be switched at the same time, is there any way to do this?

JSFiddle: https://jsfiddle.net/n2vnpd3n/

Answer

Iterate and insert based on the adjacent element.

$("#switch").click(function() {
  // iterate over text
  $('.text').each(function() {
     // insert before the immediate previous sibling
     $(this).insertBefore($(this).prev());
     // or $(this).prev().before(this);
  });
});

$("#switch").click(function() {
  $('.text').each(function() {
    $(this).prev().before(this);
  });
});
body {
  background-color: #d6e6e9;
  font-family: Helvetica;
  text-align: center;
}
.item {
  margin-bottom: 10px;
}
.image {
  background-color: #87d6e6;
  padding: 30px;
}
.text {
  background-color: #fff;
  padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="switch" value="Switch" />
<br />
<br />
<div class="item">
  <div class="image">Image</div>
  <div class="text">Text</div>
</div>

<div class="item">
  <div class="image">Image</div>
  <div class="text">Text</div>
</div>

<div class="item">
  <div class="image">Image</div>
  <div class="text">Text</div>
</div>


Or using before() method with callback.

$("#switch").click(function() {
  // iterate over image and insert before
  $('.image').before(function() {
    // get the immediately next sibling element 
    return $(this).next()
  });
});

$("#switch").click(function() {
  $('.image').before(function() {
    return $(this).next()
  });
});
body {
  background-color: #d6e6e9;
  font-family: Helvetica;
  text-align: center;
}
.item {
  margin-bottom: 10px;
}
.image {
  background-color: #87d6e6;
  padding: 30px;
}
.text {
  background-color: #fff;
  padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="switch" value="Switch" />
<br />
<br />
<div class="item">
  <div class="image">Image</div>
  <div class="text">Text</div>
</div>

<div class="item">
  <div class="image">Image</div>
  <div class="text">Text</div>
</div>

<div class="item">
  <div class="image">Image</div>
  <div class="text">Text</div>
</div>