I have two div elements inside another. At times, from user interactivity, these two items are removed, and two new elements are placed.
Is it proper to remove the existing elements first? Or just overwrite the html? Or does it even matter?
$('#item1').remove();
$('#item2').remove();
$('#itemWindow').append(newItem1);
$('#itemWindow').append(newItem2);
Or simply
$('#itemWindow').html(newItem1);
$('#itemWindow').append(newItem2);
One is less code, but should the item be removed instead? The items do not have any listeners, but if they did does that make a difference?
I’m an ActionScript developer diving into JS and jQuery. In AS, if any listeners exist, it’s proper to remove the item first to sever any ties to the object, for proper memory collection. Are these rules the same with JS and jQuery?
Thanks!
They have no difference. So you can go ahead and use the second method. as when you use this
$('#item1')and$('#item2')will be replaced. So you can skip removing those manually.As @glavić mentioned in comment if you look at the definition of
htmlmethod in jQuery source here https://github.com/jquery/jquery/blob/master/src/manipulation.js#L213You will find out at the end it has these lines
Where in this case
elemis true. So the element will beemptiedand then new element will beappended.And if they had listeners then you have to bind listeners in a way so it works with dynamically added elements like using $.on