使用JavaScript删除某个类的所有元素 [英] Remove all elements of a certain class with JavaScript

查看:2145
本文介绍了使用JavaScript删除某个类的所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HTML:

<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>

我到目前为止的JS:

var paras = document.getElementsByClassName('hi');

for(var i = 0; i < paras.length; i++) {
    paras[i].style.color = '#ff0011';
    // $('.hi').remove();
}​

在jQuery中,这太容易了。 (。喜。 $()除去(); )。我想学习JS,然后学习jQuery。

In jQuery, this would be too easy. ($('.hi').remove();). I want to learn JS, and then jQuery.

我陷入困境,谷歌没有提供。我不想成为复制/粘贴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:

节点

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,擅长它,并记住它抽象出来的东西。有一天,当你对使用jQuery时可以获得的Javascript范围,对象等有很好的把握时,请回过头来尝试学习如何在没有库的情况下更好地与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.

这篇关于使用JavaScript删除某个类的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆