Using jQuery, what\'s the performance difference between using:
$(\'#somDiv\').empty().append(\'text To Insert\')
and
$(\'
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.
Understand the meaning and functions of the extensions provided in jQuery.
$('#somDiv').empty().append('text To Insert')
-- Above code will clear the div id tag content first then will append the text to the target div:
$('#somDiv').html('text To Insert')
-- Above code replace the div tag text with the html text:
.html will overwrite the contents of the DIV.
.append will add to the contents of the DIV.
The correct syntax is
$("#somDiv").html("<span>Hello world</span>");
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>
$('#somDiv').html(value)
is equivalent to $('#somDiv').empty().append(value)
.
Source: jQuery source.