All these do it, but what is the most efficient way?
$(selector).html('');
$(selector).text('');
$(selector).children().remove();
See http://api.jquery.com/empty
$(selector).empty();
This is definitely the most clear way, and almost definitely the most efficient.
Since it's jQuery-internal it's probably more efficient than .children().remove()
, and certainly no less efficient.
I'd have to think that .html('')
and .text('')
are both less efficient since they invoke html parsers rather than just dealing with dom nodes like the other methods. And even if they happened to be more efficient, any gains in efficiency would easily be outweighted by gains in clarity of using empty(), unless you really need to optimize that section for a specific reason (in which case I'd just benchmark all the options).
In addition the answer from @Ben Lee, if you want the fastest way if displaying your new content, you may want to consider .detach()
:
var $elem = $(selector);
var $detached = $elem.children().detach();
$elem.html('new content');
$detached.remove();
This defers the data cleaning until after the new content is displayed. I haven't performance tested, but I'm pretty sure you'll see gains when removing large amounts of content.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With