jQuery empty() vs text('')

2019-06-25 11:52发布

Is there any different between

$(element).empty() and $(element).text('');

Which one is better?

1条回答
倾城 Initia
2楼-- · 2019-06-25 12:37

Result is the same, but if we look at jQuery text method implementation:

text: function (value) {
    return jQuery.access(this, function (value) {
        return value === undefined
            ? jQuery.text(this)
            : this.empty().append((this[0] && this[0].ownerDocument || document).createTextNode(value));
    }, null, value, arguments.length);
},

we will see that $(element).text(''); will actually use .empty internally. Hence latter is a little faster.

Also from semantic point of view if you want to empty some node you should definetely use .empty method, not text.

查看更多
登录 后发表回答