AppleTrue
AppleTrue

Reputation: 239

What is the difference between .empty().append() and .html()?

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

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

and

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

?

Upvotes: 9

Views: 39574

Answers (5)

Deva.TamilanbanThevar
Deva.TamilanbanThevar

Reputation: 59

difference between append() and html() in jQuery

.append() and .html() are the most useful methods in jQuery. But these are far different from one another, .append() add some value to the existing one. Where .html() do the same but it removes the old value first.

Here is an example:

<ul id="test">
<li>test</li>
</ul>

Now I will use .append() to add one <li>, For that I will write:

<script type="text/javascript>"
jQuery("#test").append("<li>test1</li>");
</script>

The output of this jQuery will be:

<ul id="test">
<li>test</li>
<li>test1</li>
</ul>

Now if I use .html() to add one <li>, For that I will write:

<script type="text/javascript>"
jQuery("#test").html("<li>test1</li>");
</script>

The output of this Script will be:

<ul id="test">
<li>test1</li>
</ul>

Here in this example .append() add one extra <li>, whether .html() removes the old one with new one. This is the main difference between .append() and .html() in jQuery.

Upvotes: 1

Roatin Marth
Roatin Marth

Reputation: 24095

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

Source: jQuery source.

Upvotes: 50

Mark Sherretta
Mark Sherretta

Reputation: 10230

.html will overwrite the contents of the DIV.

.append will add to the contents of the DIV.

Upvotes: 6

Pete Nelson
Pete Nelson

Reputation: 1338

The correct syntax is

$("#somDiv").html("<span>Hello world</span>");

Upvotes: 0

aardbol
aardbol

Reputation: 2295

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>

Upvotes: 0

Related Questions