The jQuery.appendTo method makes it easy to move a DOM element. You won’t need to be concerned with creating or destroying elements and event handlers are preserved.
Try it yourself !
In the above example, click the “HTML” tab. There are two DIVs with the IDs: “left-list” and “right-list“. DIV#left-list has an unordered list with the days of the week, and DIV#right-list is empty. Now click the “JS” tab. You’ll see that there is a click-event handler for
$('#left-list li'). This means that when any of the list items are clicked, the anonymous function you see will be executed.
Go ahead and click each of the days of the week and you’ll see that it is moved to the DIV#right-list element. After each element is moved, if you click it, nothing happens.
.appendTo( $('#right-list') ). Here we are telling jQuery: “Move this element to the #right-list element, and make it the last child“. So, we are appending it to DIV#right-list. We then chain this:
.unbind('click');. The reason we do that is: the jQuery appendTo method retains any event bindings for elements that are moved. Most of the time, this is probably what you want. But in this case, we do not want the event bindings to travel with the element because once a list item is moved inside of the #right-list element, we no longer want it to have a click-event handler. But that is simply for this example.