CGeek
CGeek

Reputation: 25

Replace one div with another - jquery

I have 4 divs and in each one there are top and down arrows. If user click top arrow - current div change place with higher div and conversely.

How can I do this? This code is for "bottom arrow" and doesnt work...

$("button.down").click(function(){

var aDiv = $(this).parent();
var dDiv = $(this).parent().next("div");

$(this).parent().next("div").replaceWith(aDiv);
$(this).parent().replaceWith(dDiv);

});

http://jsfiddle.net/gjkhf81u/

Upvotes: 2

Views: 1722

Answers (3)

Ruan Mendes
Ruan Mendes

Reputation: 92274

As T.J. Crowder mentioned, you want to use insertBefore and insertAfter.

When you insert a node in a different place in the DOM, it gets moved.

$("button.down").click(function(){
  var aDiv = $(this).parents(".container");
  var nextDiv = aDiv.next(".container");
  aDiv.insertAfter(nextDiv);
});

$("button.up").click(function(){
  var aDiv = $(this).parents(".container");
  var prevDiv = aDiv.prev(".container");
  aDiv.insertBefore(prevDiv);
});
.container {
    width: 100%;
    height: 25px; 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="background-color: green;" class="container">
<button class="up">Up</button>
<button class="down">Down</button>
</div>

<div style="background-color: red;" class="container">
<button class="up">Up</button>
<button class="down">Down</button>
</div>

<div style="background-color: yellow;" class="container">
<button class="up">Up</button>
<button class="down">Down</button>
</div>

<div style="background-color: blue;" class="container">
<button class="up">Up</button>
<button class="down">Down</button>
</div>

Upvotes: 0

Jack hardcastle
Jack hardcastle

Reputation: 2875

Alternatively, you could swap the contents of the divs?

<div class="x"> Hello World </div>
<div class="y"> Bye World </div>

    $("button.down").click(function() {
        var temp = $(".x").html();
        $(".x").html() = $(".y").html();
        $(".y").html() = temp;
    });

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074028

You're probably looking for insertBefore:

var div = $(theCurrentDiv);
var prev = div.prev();
if (prev[0]) {
    div.insertBefore(div.prev());
}

That code moves the current div to in front of its sibling, if any. There's also the related before, which goes the other way.

insertBefore example:

$("input[type=button]").click(function() {
  var div = $(".current");
  var prev = div.prev();
  if (prev[0]) {
    div.insertBefore(prev);
  }
});
.current {
  color: green;
  font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="button" value="Up">
<div>
  <div>one</div>
  <div>two</div>
  <div>three</div>
  <div class="current">four</div>
</div>

Upvotes: 2

Related Questions