What is the difference between .empty().append() a

2020-02-11 05:58发布

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

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

and

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

?

6条回答
家丑人穷心不美
2楼-- · 2020-02-11 06:36

The correct syntax is

$("#somDiv").html("<span>Hello world</span>");
查看更多
何必那么认真
3楼-- · 2020-02-11 06:44

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.

查看更多
可以哭但决不认输i
4楼-- · 2020-02-11 06:47

.html will overwrite the contents of the DIV.

.append will add to the contents of the DIV.

查看更多
SAY GOODBYE
5楼-- · 2020-02-11 06:47

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>
查看更多
姐就是有狂的资本
6楼-- · 2020-02-11 06:47

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:

查看更多
老娘就宠你
7楼-- · 2020-02-11 06:49

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

Source: jQuery source.

查看更多
登录 后发表回答