5

Is there any different between

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

Which one is better?

Atif
  • 10,623
  • 20
  • 63
  • 96
  • `empty()` will get rid of HTML and Text, while `text('')` will get rid of text. they are 2 different things. So it depends on what you need – Jeff Shaver Apr 04 '13 at 12:12
  • Duplicate of http://stackoverflow.com/questions/5723789/whats-the-difference-between-jquery-fn-empty-and-jquery-fn-html – codefreak Apr 04 '13 at 12:12
  • Just a guess at the internals, clearing something should be faster than assigning it to an empty string. [this](http://stackoverflow.com/a/5723797/485048) proves my assumption. – Benjamin Kaiser Apr 04 '13 at 12:13

1 Answers1

9

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.

dfsq
  • 191,768
  • 25
  • 236
  • 258