开发者

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

All these do it, but what is开发者_Go百科 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜