Search code examples
javascriptjqueryhtmljquery-after

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


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!


Solution

  • 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