简体   繁体   English

如何删除DOM中没有的元素?

[英]How can I remove an element that is not in the DOM?

var paragraphElement = document.createElement('p');

paragraphElement is not in the DOM. paragraphElement不在DOM中。 How can I remove it? 我该如何删除它? I know I can use removeChild if it's in the DOM. 我知道如果它在DOM中,我可以使用removeChild I don't tend to add paragraphElement to the DOM and then remove it. 我不倾向于将paragraphElement添加到DOM中,然后将其删除。 Any solution? 有解决方案吗

Thank you. 谢谢。

If an object isn't referenced anymore it will be marked for the garbage collection. 如果一个对象不再被引用,它将被标记为垃圾收集。 So when you leave the context where p is valid and the element isn't referenced in any other way the garbage collection will free the memory whenever it will run next. 因此,当你离开p有效的上下文并且没有以任何其他方式引用元素时,垃圾收集将在下次运行时释放内存。 How the garbage collection achieves this depends on the JavaScript engine. 垃圾收集如何实现这取决于JavaScript引擎。

You can also assign p a new non-reference value like 0 , or use p = null . 您还可以为p指定一个新的非引用值,如0 ,或使用p = null Notice that .removeChild won't remove the child from memory, only from the DOM, but will free it for garbage collection if there's no other reference on this node. 请注意, .removeChild不会仅从DOM中删除内存中的子项,但如果此节点上没有其他引用,则会释放它以进行垃圾回收。

For more information, check MDN: Memory Management . 有关更多信息,请查看MDN:内存管理

If it's not in the DOM, then all you have to do is clear any JS references to it and the garbage collector will remove it for you. 如果它不在DOM中,那么您所要做的就是清除对它的任何JS引用,垃圾收集器将为您删除它。 This is essentially no different than a javascript object or a javascript array. 这基本上与javascript对象或javascript数组没有什么不同。 If you clear any references to it, the garbage collector will clean it up. 如果清除对它的任何引用,垃圾收集器将清理它。

So, if you create it like this: 所以,如果你这样创建它:

var paragraphElement = document.createElement('p');

Then, all you have to do to get rid of it is clear that reference: 然后,你需要做的就是摆脱它,参考:

var paragraphElement = null;

With no javascript references to the element, the garbage collector will remove it. 由于没有对元素的javascript引用,垃圾收集器将删除它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM