Javascript 如何从 DOM 中删除某个类的所有元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10842471/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to remove all elements of a certain class from the DOM?
提问by jonathanbell
var paras = document.getElementsByClassName('hi');
for (var i = 0; i < paras.length; i++) {
paras[i].style.color = '#ff0011';
// $('.hi').remove();
}
<p class="hi">dood</p>
<p class="hi">dood</p>
<p class="hi">dood</p>
<p class="hi">dood</p>
<p class="hi">dood</p>
<p>not class 'hi'</p>
In jQuery, this would be very easy: $('.hi').remove();
. I want to learn JS, and then jQuery.
在jQuery中,这将是非常容易的:$('.hi').remove();
。我想学习 JS,然后 jQuery。
I am stuck and Google has not provided. I do not want to become a copy/paste jQuery programmer. I am just starting to learn JS. Thanks.
我被卡住了,谷歌没有提供。我不想成为复制/粘贴 jQuery 程序员。我刚开始学习JS。谢谢。
回答by Paul
To remove an element you do this:
要删除元素,请执行以下操作:
el.parentNode.removeChild(el);
MDN is a great reference. Here are a few relevant pages:
MDN 是一个很好的参考。以下是一些相关页面:
However you'll run into issues if you loop like that since getElementsByClassNamereturns a live list, when you remove a node the element is removed from the list as well so you shouldn't increment or you will end up skipping every other element. Instead just continually remove the first element in the list, until there is no first element:
但是,如果您像这样循环,则会遇到问题,因为getElementsByClassName返回一个实时列表,当您删除节点时,元素也会从列表中删除,因此您不应该增加,否则最终会跳过所有其他元素。而是不断地删除列表中的第一个元素,直到没有第一个元素:
var paras = document.getElementsByClassName('hi');
while(paras[0]) {
paras[0].parentNode.removeChild(paras[0]);
}?
IMO jQuery is great at showing you what is possible to do in Javascript. I actually recommend that after about a week or two of plain JS you learn jQuery, get good at it, and remember what it's abstracting away. One day when you have an excellent grasp of Javascript scoping, objects, and such which you can obtain while using jQuery, go back and try learning how to interact better with the DOM without a library. That way you'll have an easier time learning plain JS and you'll appreciate the abstraction that libraries can provide you even more, while learning that when you only need one or two things a library provides you may be able to write them yourself without including the entire library.
IMO jQuery 非常擅长向您展示在 Javascript 中可以做什么。我实际上建议您在学习 jQuery 大约一两个星期后,学习 jQuery,熟练掌握它,并记住它抽象出来的东西。有一天,当您对使用 jQuery 时可以获得的 Javascript 范围、对象等有很好的掌握时,回去尝试学习如何在没有库的情况下更好地与 DOM 交互。这样你就可以更轻松地学习纯 JS 并且你会欣赏库可以为你提供更多的抽象,同时学习当你只需要一个库提供的一两件东西时,你可以自己编写它们而不需要包括整个图书馆。
回答by Phrogz
[].forEach.call(document.querySelectorAll('.hi'),function(e){
e.parentNode.removeChild(e);
});
Here I'm using Array.prototype.forEach
to easily traverse all elements in an array-like object, i.e. the static NodeList returned by querySelectorAll
, and then using removeChild()
to remove the item from the DOM.
在这里,我使用Array.prototype.forEach
轻松遍历类数组对象中的所有元素,即由 返回的静态 NodeList querySelectorAll
,然后使用removeChild()
从 DOM 中删除项目。
For older browsers that don't support querySelectorAll()
or forEach()
:
对于不支持querySelectorAll()
或 的旧浏览器forEach()
:
var classMatcher = /(?:^|\s)hi(?:\s|$)/;
var els = document.getElementsByTagName('*');
for (var i=els.length;i--;){
if (classMatcher.test(els[i].className)){
els[i].parentNode.removeChild(els[i]);
}
}
Note that because getElementsByTagName
returns a liveNodeList, you must iterate over the items from back to front while removing them from the DOM.
请注意,因为getElementsByTagName
返回一个活动的NodeList,所以您必须从后到前迭代这些项目,同时将它们从 DOM 中删除。
There are also some older browsers that don't support querySelectorAll
but that do support getElementsByClassName
, which you could use for increased performance and reduced code.
还有一些不支持querySelectorAll
但支持 的旧浏览器,getElementsByClassName
您可以使用它们来提高性能并减少代码。
回答by leonheess
Simple ES6 answer:
简单的 ES6 答案:
document.querySelectorAll('.classname').forEach(e => e.remove());
Explanation:
解释:
document.querySelectorAll()
loops through the elements in the document returning a NodeListof all elements with the specified selector (e.g.'.class'
,'#id'
,'button'
)forEach()
loops through the NodeList and executes the specified action for each elemente => e.remove()
removes the element from the DOM
document.querySelectorAll()
循环遍历文档中的元素,返回具有指定选择器(例如, , )的所有元素的NodeList'.class'
'#id'
'button'
forEach()
循环遍历 NodeList 并对每个元素执行指定的动作e => e.remove()
从 DOM 中移除元素
Note, however, that this solution is notsupported by every browser (namely IE)
回答by Matt Dodge
Afaik only a parent can remove a child in native JS. So you would first have to get that elements parent, then use the parent to remove the element. Try this:
Afaik 只有父级才能在原生 JS 中删除子级。因此,您首先必须获得该元素的父元素,然后使用父元素删除该元素。尝试这个:
var parent = paras[i].parentNode;
parent.removeChild(paras[i]);