What is the most efficient way to remove an element using jQuery

All do it, but what is the most effective way?

$(selector).html(''); $(selector).text(''); $(selector).children().remove(); 
+8
jquery
source share
2 answers

See http://api.jquery.com/empty

 $(selector).empty(); 

This is definitely the most understandable way and almost certainly the most effective.

Since it is jQuery-internal, it is probably more efficient than .children().remove() , and, of course, no less efficient.

I would have to think that .html('') and .text('') are less efficient since they call html parsers and not just deal with dom nodes like other methods. And even if they turned out to be more efficient, any gain in efficiency could be easily transferred due to a gain in the clarity of using empty (), if you really do not need to optimize this section for a certain reason (in this case, I would just evaluate all the options )

+12
source share

Additionally, the answer is from @Ben Lee , if you want the fastest way to display your new content, you can consider .detach() :

 var $elem = $(selector); var $detached = $elem.children().detach(); $elem.html('new content'); $detached.remove(); 

Rejects data cleansing until new content is displayed. I have not tested the performance, but I am sure that you will see a profit when deleting a large amount of content.

+3
source share

Source: https://habr.com/ru/post/650952/


All Articles