views:

376

answers:

4

Using jQuery, what's the performance difference between using:

$('#somDiv').empty().append('text To Insert')

and

$('#somDiv').html('text To Insert')

?

+2  A: 

.html will overwrite the contents of the DIV.

.append will add to the contents of the DIV.

Nebakanezer
Does append use DOM? Whereas innerHTML does not?
AppleTrue
Please note that I have included the empty() function to that append is overwriting like .html. Is .append faster than .html?
AppleTrue
Not answering the OP's question...
J-P
@J-P: in all fairness from the timestamps it seems the OP heavily edited the question from typo-ridden to sensible.
Crescent Fresh
A: 

In simple words:

$('#somDiv').append('blabla')

works like this:

<div id='somDiv'>some text</div>

becomes:

<div id='somDiv'>some textblabla</div>

And innerHTML replaces the contents, so it becomes this:

<div id='somDiv'>blabla</div>
EarthMind
I've updated my original post to include the empty() function so that they act the same
AppleTrue
They are exactly the same in terms of result but innerHTML would probably be faster on big files as it just uses the native function, which is only 1 call.
EarthMind
Is .append faster than .html?
AppleTrue
+8  A: 

$('#somDiv').html(value) is equivalent to $('#somDiv').empty().append(value).

Source: jQuery source.

Roatin Marth
I've updated to make it .html(). Now, what's the difference?
AppleTrue
@AppleTrue: Updated answer
Roatin Marth
Is .append faster than .html?
AppleTrue
@AppleTrue: slow down on the updates man! ;) I've updated my answer to your latest question....
Roatin Marth
`.empty().append(...)` will be marginally faster since `.html(...)` is essentially a wrapper for the same thing. Don't use `.empty().append(...)` for the sake of speed, since you wouldn't notice a difference in even several thousand calls, and it would be confusing to someone reading your code.
Blixt
A: 

The correct syntax is

$("#somDiv").html("<span>Hello world</span>");
Pete Nelson
I've updated my original post. Now what's the difference? (Thanks)
AppleTrue
Functionally, now there is no difference.
Pete Nelson