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

前端 未结 6 1198
心在旅途
心在旅途 2020-12-18 08:27

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

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

and

$(\'         


        
相关标签:
6条回答
  • 2020-12-18 09:04

    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.

    0 讨论(0)
  • 2020-12-18 09:14

    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:

    0 讨论(0)
  • 2020-12-18 09:17

    .html will overwrite the contents of the DIV.

    .append will add to the contents of the DIV.

    0 讨论(0)
  • 2020-12-18 09:19

    The correct syntax is

    $("#somDiv").html("<span>Hello world</span>");
    
    0 讨论(0)
  • 2020-12-18 09:23

    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>
    
    0 讨论(0)
  • 2020-12-18 09:25

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

    Source: jQuery source.

    0 讨论(0)
提交回复
热议问题