jQuery empty() vs remove()

后端 未结 3 1772
孤街浪徒
孤街浪徒 2020-12-12 15:25

What\'s the difference between empty() and remove()methods in jQuery, and when we call any of these methods, the objects being created

相关标签:
3条回答
  • 2020-12-12 15:52

    The documentation explains it very well. It also contains examples:

    • .remove()
    • .empty()

    before:

    <div class="container">
      <div class="hello">Hello</div>
      <div class="goodbye">Goodbye</div>
    </div>
    

    .remove():

    $('.hello').remove();
    

    after:

    <div class="container">
      <div class="goodbye">Goodbye</div>
    </div>
    

    before:

    <div class="container">
      <div class="hello">Hello</div>
      <div class="goodbye">Goodbye</div>
    </div>
    

    .empty():

    $('.hello').empty();
    

    after:

    <div class="container">
      <div class="hello"></div>
      <div class="goodbye">Goodbye</div>
    </div>
    

    As far as memory is concerned, once an element is removed from the DOM and there are no more references to it the garbage collector will reclaim the memory when it runs.

    0 讨论(0)
  • 2020-12-12 15:53
    • empty() will empty the selection of its contents, but preserve the selection itself.
    • remove() will empty the selection of its contents and remove the selection itself.

    Consider:

    <div>
        <p><strong>foo</strong></p>
    </div>
    
    $('p').empty();  // --> "<div><p></p></div>"
    
    // whereas,
    $('p').remove(); // --> "<div></div>"
    

    Both of them remove the DOM objects and should release the memory they take up, yes.


    Here are links to documentation, which also contains examples:

    • .remove()
    • .empty()
    0 讨论(0)
  • 2020-12-12 15:59

    $("body").empty() -- it' removes the HTML DOM elements inside the body tag -

    when you declare $("body").remove() - it remove the entire HTML DOM along with body TAG .

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