Reputation: 693
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!
Upvotes: 5
Views: 365
Reputation: 13461
They have no difference. So you can go ahead and use the second method. as when you use this
$('#itemWindow').html(newItem1);
$('#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 html
method in jQuery source here https://github.com/jquery/jquery/blob/master/src/manipulation.js#L213
You will find out at the end it has these lines
if ( elem ) {
this.empty().append( value );
}
Where in this case elem
is true. So the element will be emptied
and then new element will be appended
.
And if they had listeners then you have to bind listeners in a way so it works with dynamically added elements like using $.on
Upvotes: 3
Reputation: 452
if item has any listener then first method is more appropriate. .remove()
removes items itself and all bound event. if item is removed but not event, error may occur in future. but if no bounded event, second method can be used - coz less code.
Upvotes: 0
Reputation: 270
If you want to be specific about what you are actually removing, say in the case that you have one element that needs to be removed, but not the other, then I recommend the first method. If you are simply going to be replacing everything every time, then feel free to use either or, the only issue then is what is more readable for you.
Upvotes: 0
Reputation: 24515
$('#item1').remove(); will remove the element with id item1
$('#item1').html(newItem1); will set the html within the element with id item1
Upvotes: 0