Moving Elements with jQuery

Using before and after to move elements in jQuery. Important point to remember - bind element as a JQUERY OBJECT to a variable so that it is moved and not cloned.

by Marcus Baptiste

HTML

<div id="one"> first paragraph</div>
<div id="two"> second paragraph</div>

JavaScript

$(document).ready( function() {
    //MOVING OBJECTS WITH BEFORE AFTER
    //save element as JQUERY OBJECT to variable
    //this makes it an established (binded) element so it will not 
    //be cloned but moved
    
    var p = $("<p>This is a par</p>");
    $("#one").after(p);
    $(p).click(function() {
        if ($(p).prev().attr("id") === "two") {
            $("#two").before(p);
        } else {
            $("#two").after(p);
        }
    });
  
});