Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the most efficient way to empty an element with jQuery

Tags:

jquery

All these do it, but what is the most efficient way?

$(selector).html('');
$(selector).text('');
$(selector).children().remove();
like image 935
Jake Avatar asked Jan 11 '11 22:01

Jake


2 Answers

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).

like image 171
Ben Lee Avatar answered Sep 19 '22 13:09

Ben Lee


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.

like image 27
user113716 Avatar answered Sep 21 '22 13:09

user113716