Is it good practice to check t开发者_StackOverflowhat element exist before remove it or it is not necessary ? For example:
if(('#el').length > 0) {
$('#el').remove();
}
is same as
$('#el').remove();
All jQuery selectors return a collection (perhaps empty) of jQuery objects and so if $('#el')
(or more likely $('.class')
) returned a number of objects remove()
would remove them all. Likewise, if your selector doesn't return any objects remove()
will not remove any.
So no. It isn't necessary.
I daresay, first version adds absolutely nothing in terms of functionality or performance. If your selector 'selects' 0 elements, then jquery won't remove anything.
I would say NO, it's not necessary.
Especially in your example, since the state of your program will be exactly the same in both cases after the code has run, regardless of the state before that code ran (removal is idempotent).
It depends on whether you need that element or not.
I suppose it's a bit more explicit in reading it but that's the only "benefit" I can think of. Doesn't seem worth it at all. But if you need to do something in the case you do indeed remove elements you could first check if there are any to remove.
精彩评论