jQuery empty() vs remove()

偶尔善良 提交于 2019-12-17 21:41:46

问题


What's the difference between empty() and remove()methods in jQuery, and when we call any of these methods, the objects being created will be destroyed and memory released?


回答1:


  • empty() will remove all the contents of the selection.
  • remove() will remove the selection and its contents.

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.




回答2:


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.




回答3:


$("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 .



来源:https://stackoverflow.com/questions/3090662/jquery-empty-vs-remove

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!