bavaza bavaza - 9 days ago 5
jQuery Question

Does jquery `append()` remove duplicate objects?

I'm sorting a table using jQuery, roughly following the code found here. The code sketch is as follows:

$('.sort-table').click(function(e) {
// cache objects
$table = $('#sort-table'), // cache the target table DOM element
$rows = $('tbody > tr', $table); // cache rows from target table body

// sort items

// assign to table - what is going on?
$rows.each(function(index, row){
$table.append(row); // <-- how come $table remains the same size?

While the code works fine, I'm puzzeled by the code that appends the rows back to the table, which simply iterates over the sorted rows, appending each at the end of

At no stage did we emtpy
from its previous children.

  • Since
    was never emptied, how come
    remains the same size?

  • Does
    also enforces uniquness in the target container?


This is simply how the DOM works. You can't have an element in two different places. If an element is already in a document and you put it somewhere else, it will be moved from its current position. It is, I suppose, a little like a Set, but that is not how it is specified. So it's not removing duplicate objects, because there never are duplicate objects: it's simply moving the same object, which can only exist in one place.

From the MDN documentation for the underlying method, Node.appendChild:

The Node.appendChild() method adds a node to the end of the list of children of a specified parent node. If the given child is a reference to an existing node in the document, appendChild() moves it from its current position to the new position (there is no requirement to remove the node from its parent node before appending it to some other node).

If you want to duplicate elements, you need to clone them (DOM, jQuery).