开发者

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

开发者 https://www.devze.com 2022-12-14 12:32 出处:网络
Using jQuery, what\'s the performance difference between using: $(\'#somDiv\').empty().append(\'text To Insert\')

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

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

开发者_如何学JAVAand

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

?


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

Source: jQuery source.


.html will overwrite the contents of the DIV.

.append will add to the contents of the DIV.


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.


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>


The correct syntax is

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号