问题描述
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>
在jQuery中,这将非常简单:$('.hi').remove();
.我想学习JS,然后学习jQuery.
In jQuery, this would be very easy: $('.hi').remove();
. I want to learn JS, and then jQuery.
我被困,Google没有提供.我不想成为复制/粘贴jQuery程序员.我才刚刚开始学习JS.谢谢.
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.
推荐答案
要删除元素,请执行以下操作:
To remove an element you do this:
el.parentNode.removeChild(el);
MDN是一个很好的参考.以下是一些相关页面:
MDN is a great reference. Here are a few relevant pages:
Node
parentNode
removeChild
但是,由于 getElementsByClassName 那样循环播放,您会遇到问题.返回活动列表,当您删除节点时,该元素也会从列表中删除,因此您不应递增,否则最终将跳过所有其他元素.而是连续删除列表中的第一个元素,直到没有第一个元素为止:
However you'll run into issues if you loop like that since getElementsByClassName returns 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:
var paras = document.getElementsByClassName('hi');
while(paras[0]) {
paras[0].parentNode.removeChild(paras[0]);
}
IMO jQuery非常擅长向您展示使用Javascript可以做什么.我实际上建议在大约一两个星期的普通JS之后学习jQuery,熟练掌握它,并记住它的抽象含义.有一天,您对Javascript范围,对象等有了很好的掌握,可以在使用jQuery时获得这些知识,然后回去尝试学习如何在没有库的情况下更好地与DOM交互.这样一来,您将可以更轻松地学习普通的JS,并且会欣赏到库可以为您提供更多的抽象概念,同时了解到当您只需要一两个东西时,库就可以为您自己编写它们,而无需包括整个库.
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.
这篇关于如何从DOM中删除某个类的所有元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!