Baldráni
Baldráni

Reputation: 5640

Missunderstanding append() or a treatement in Js/JQuery

I need a bit of comprehension on this one pls :

Its a function to sort by price product. Only problem is that I dont get why I dont have to empty my table before appending the products

Here is a playground

This is the code

$length = $('[data-th="Prix : "]').length;
$dispo = $('.productsDispo');
$temp = 0;
for(var i = 0; i < $length; i++)
{   
    for(var j = i; j < $length; j++)
    {
        $prixI = $($dispo[i]).find($('[data-th="Prix : "]')).text().slice(0, $($dispo[i]).find($('[data-th="Prix : "]')).text().length-2);
        $prixJ = $($dispo[j]).find($('[data-th="Prix : "]')).text().slice(0, $($dispo[j]).find($('[data-th="Prix : "]')).text().length-2);

        if(parseInt($prixI) < parseInt($prixJ))
        {
          $temp = $dispo[i];
          $dispo[i] = $dispo[j];
          $dispo[j] = $temp;
        }
    }
}
for(var i = 0; i < $length; i++)
{  
    $('.rwd-table tbody').append($dispo[i])
}

Upvotes: 1

Views: 49

Answers (2)

user3297291
user3297291

Reputation: 23372

jQuery's append does not make a clone of an element that you pass to it. It 'cuts' the element from its old location and 'pastes' it into a new one.

Here's a simpler example that shows this behavior, if anyone needs it illustrated.

Upvotes: 1

Andrei
Andrei

Reputation: 56688

That's because of how append works in jQuery. From docs:

If an element selected this way is inserted into a single location elsewhere in the DOM, it will be moved into the target (not cloned):

Since you do the sorting and appending manipulating the very DOM objects you selected, they are already in the table, and you basically move them inside the table with append.

Upvotes: 3

Related Questions