use of Jquery .after() for moving an element around

2.7k views Asked by At

I'm reading the jquery manual regarding the .after() function:

$('.container').after($('h2'));

and it says

"If an element selected this way is inserted elsewhere, it will be moved rather than cloned"

So if I have multiple <div class='before' onclick='afterfunction();'><div>,

and I would want to place <div class='after'></div> after whichever div is clicked (have it move, not clone) would I do something like this?

var afterdiv = "<div class='after'></div>";
function afterfunction() {
    $(this).after(afterdiv);
}

Thanks for all your help!

2

There are 2 answers

2
Roko C. Buljan On BEST ANSWER

Like you said:

An element in the DOM can also be selected and inserted after another element: $('.container').after($('h2'));
If an element selected this way is inserted elsewhere, it will be moved rather than cloned:

But you missed the bold part.

$('.before').click(function() {
  afterfunction(this);
});

// this will not work cause you'll append a string to your DOM
// var afterdiv = "<div class='after'>ola</div>";
// and will repeatedly be appended after each action.

// instead define your element by wrapping it into a $( )
  var afterdiv = $("<div class='after'>ola</div>");
// now 'afterdiv' variable is binded to that element only once inside the DOM 

function afterfunction(elem) {
   $(elem).after(afterdiv);
}

And you don't need to .remove() it (like wrongly suggested in an answer here.)

demo jsFiddle

4
The System Restart On

Make .before div like this:

<div class='before'><div/>

Then try,

$('.before').on('click', function() {
  afterfunction(this);
});

function afterfunction(el) {
  var afterdiv = "<div class='after'></div>";
  $('.after').remove(); // remove previous `.after`
  $(el).after(afterdiv); // add newly after the clicked div
}

DEMO