What is the difference between jQuery: text() and html() ?

后端 未结 16 1727
傲寒
傲寒 2020-11-22 03:45

What the difference between text() and html() functions in jQuery ?

$(\"#div\").html(\'Linkhello\         


        
16条回答
  •  日久生厌
    2020-11-22 04:33

    ((please update if necessary, this answer is a Wiki))

    Sub-question: when only text, what is faster, .text() or .html()?

    Answer: .html() is faster! See here a "behaviour test-kit" for all the question.

    So, in conclusion, if you have "only a text", use html() method.

    Note: Doesn't make sense? Remember that the .html() function is only a wrapper to .innerHTML, but in the .text() function jQuery adds an "entity filter", and this filter naturally consumes time.


    Ok, if you really want performance... Use pure Javascript to access direct text-replace by the nodeValue property. Benchmark conclusions:

    • jQuery's .html() is ~2x faster than .text().
    • pure JS' .innerHTML is ~3x faster than .html().
    • pure JS' .nodeValue is ~50x faster than .html(), ~100x than .text(), and ~20x than .innerHTML.

    PS: .textContent property was introduced with DOM-Level-3, .nodeValue is DOM-Level-2 and is faster (!).

    See this complete benchmark:

    // Using jQuery:
    simplecron.restart(); for (var i=1; i<3000; i++) 
        $("#work").html('BENCHMARK WORK');
    var ht = simplecron.duration();
    simplecron.restart(); for (var i=1; i<3000; i++) 
        $("#work").text('BENCHMARK WORK');
    alert("JQuery (3000x): \nhtml="+ht+"\ntext="+simplecron.duration());
    
    // Using pure JavaScript only:
    simplecron.restart(); for (var i=1; i<3000; i++)
        document.getElementById('work').innerHTML = 'BENCHMARK WORK';
    ht = simplecron.duration();
    simplecron.restart(); for (var i=1; i<3000; i++) 
        document.getElementById('work').nodeValue = 'BENCHMARK WORK';
    alert("Pure JS (3000x):\ninnerHTML="+ht+"\nnodeValue="+simplecron.duration());
    

提交回复
热议问题