使用JavaScript删除元素

使用JavaScript删除元素Therearetwom thetradition counter intuitiveway andthenewdir 使用 JavaScript 从网页中删除元素的方法有两种 传统的 违反直觉的方法和新的直接 DOM4 方法

There are two methods of removing elements from web pages with JavaScript: the traditional, counter-intuitive way, and the new direct DOM4 method.

使用JavaScript从网页中删除元素的方法有两种:传统的,违反直觉的方法和新的直接DOM4方法。

The traditional method is rather round-about: you cannot simply remove an element, but must do so via a reference to its parent. Given the following markup:

传统方法相当复杂:您不能简单地删除元素,而必须通过引用其父元素来删除它。 给定以下标记:

 
   

Yggdrasil Explorer

Yggdrasil is the "WorldTree" of Norse mythology, a cosmos-spanning ash that connects the nine worlds.

If I wanted to remove description from the DOM, I could do the following.

如果我想从DOM中删除description ,可以执行以下操作。

var description = document.getElementById("description"); description.parentNode.removeChild(description);

This method is bizarrely self-reflective, but it has the advantage of working in every browser. Visually, it has the same effect as setting description to display: none in CSS, but of course the element is completely removed from the DOM, not merely hidden.

这种方法具有奇特的自我反省功能,但具有在每种浏览器中均可使用的优势。 视觉上,它具有与设定相同的效果description于display: none在CSS ,但当然该元素被完全从移除所述DOM ,不仅隐藏。

The removed element remains as a reference in JavaScript, floating in memory: if I wanted to attach the removed description to the norsemap element, I could do the following:

被移除的元素仍保留在JavaScript中,并在内存中浮动:如果我想将被移除的description附加到norsemap元素,则可以执行以下操作:

var norsemap = document.getElementById("norsemap"); norsemap.appendChild(description);

An upcoming article will explore more possibilities of this “cut and paste” ability of JavaScript, particularly in how it can be used in responsive design.

即将发表的文章将探讨JavaScript的这种“剪切和粘贴”功能的更多可能性,尤其是如何将其用于响应式设计中。

。去掉() (.remove())

DOM4 provides a far more direct method. Returning to the original code, we can simply use:

DOM4提供了一种更为直接的方法。 回到原始代码,我们可以简单地使用:

var description = document.getElementById("description"); description.remove();

Great, right? There’s just one problem: the method only works on recent browsers (Chrome & Firefox 23+, Opera 10+, and Safari 7+), and not at all in Internet Explorer… not even IE11, at least as of this writing. However, polyfills exist, such as DOM4 & DOMShim.

太好了吧? 只有一个问题:该方法仅适用于最新的浏览器(Chrome和Firefox 23 +,Chrome Opera 10+和Safari 7+),而在Internet Explorer中根本不起作用,甚至在撰写本文时,甚至都不是IE11。 但是,存在polyfill ,例如DOM4和DOMShim 。

翻译自: https://thenewcode.com/947/Removing-Elements-With-JavaScript

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/202823.html原文链接:https://javaforall.net

(0)
上一篇 2026年3月19日 下午11:13
下一篇 2026年3月19日 下午11:13


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号