Javascript 按类名删除元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4777077/
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
Removing elements by class name?
提问by Brett
I have the below code to find elements with their class name:
我有以下代码来查找具有类名的元素:
// Get the element by their class name
var cur_columns = document.getElementsByClassName('column');
// Now remove them
for (var i = 0; i < cur_columns.length; i++) {
}
I just don't know how to remove them..... do I HAVE to reference the parent or something? What's the best way to handle this?
我只是不知道如何删除它们......我是否必须引用父级或其他内容?处理这个问题的最佳方法是什么?
@Karim79:
@卡里姆79:
Here is the JS:
这是JS:
var col_wrapper = document.getElementById("columns").getElementsByTagName("div");
var len = col_wrapper.length;
alert(len);
for (var i = 0; i < len; i++) {
if (col_wrapper[i].className.toLowerCase() == "column") {
col_wrapper[i].parentNode.removeChild(col_wrapper[i]);
}
}
Here is the HTML:
这是 HTML:
<div class="columns" id="columns">
<div class="column"><input type="checkbox" name="col_list[]" value="cows">cows</div>
<div class="column"><input type="checkbox" name="col_list[]" value="cows">cows</div>
<div class="column"><input type="checkbox" name="col_list[]" value="cows">cows</div>
<div class="column"><input type="checkbox" name="col_list[]" value="cows">cows</div>
<div name="columnClear" class="contentClear" id="columnClear"></div>
</div>
Edit:Well ended up just using the jQuery option.
编辑:最后只使用 jQuery 选项。
回答by Lior Cohen
Using jQuery (which you really could be using in this case, I think), you could do this like so:
使用 jQuery(我认为在这种情况下你真的可以使用它),你可以这样做:
$('.column').remove();
Otherwise, you're going to need to use the parent of each element to remove it:
否则,您将需要使用每个元素的父元素来删除它:
element.parentNode.removeChild(element);
回答by Veikko Karsikko
If you prefer not to use JQuery:
如果您不想使用 JQuery:
function removeElementsByClass(className){
var elements = document.getElementsByClassName(className);
while(elements.length > 0){
elements[0].parentNode.removeChild(elements[0]);
}
}
回答by Roko C. Buljan
Using ES6you could do like:
使用ES6你可以这样做:
const removeElements = (elms) => elms.forEach(el => el.remove());
// Use like:
removeElements( document.querySelectorAll(".remove") );
<p class="remove">REMOVE ME</p>
<p>KEEP ME</p>
<p class="remove">REMOVE ME</p>
回答by tocqueville
In pure Javascript, without jQuery or ES6, you could do:
在没有 jQuery 或 ES6 的纯 Javascript 中,您可以执行以下操作:
const elements = document.getElementsByClassName("my-class");
while (elements.length > 0) elements[0].remove();
回答by Уляна Р?зник
This works for me
这对我有用
while (document.getElementsByClassName('my-class')[0]) {
document.getElementsByClassName('my-class')[0].remove();
}
回答by karim79
Brett - are you aware that getElementyByClassName
support from IE 5.5 to 8 is not thereaccording to quirksmode?. You would be better off following this pattern if you care about cross-browser compatibility:
Brett - 你知道根据 quirksmode不getElementyByClassName
支持 IE 5.5 到 8吗?。如果您关心跨浏览器兼容性,最好遵循此模式:
- Get container element by ID.
- Get needed child elements by tag name.
- Iterate over children, test for matching className property.
elements[i].parentNode.removeChild(elements[i])
like the other guys said.
- 通过 ID 获取容器元素。
- 通过标签名称获取所需的子元素。
- 迭代子项,测试匹配的 className 属性。
elements[i].parentNode.removeChild(elements[i])
就像其他人说的。
Quick example:
快速示例:
var cells = document.getElementById("myTable").getElementsByTagName("td");
var len = cells.length;
for(var i = 0; i < len; i++) {
if(cells[i].className.toLowerCase() == "column") {
cells[i].parentNode.removeChild(cells[i]);
}
}
EDIT: Here is the fixed version, specific to your markup:
编辑:这是固定版本,特定于您的标记:
var col_wrapper = document.getElementById("columns").getElementsByTagName("div");
var elementsToRemove = [];
for (var i = 0; i < col_wrapper.length; i++) {
if (col_wrapper[i].className.toLowerCase() == "column") {
elementsToRemove.push(col_wrapper[i]);
}
}
for(var i = 0; i < elementsToRemove.length; i++) {
elementsToRemove[i].parentNode.removeChild(elementsToRemove[i]);
}
The problem was my fault; when you remove an element from the resulting array of elements, the length changes, so one element gets skipped at each iteration. The solution is to store a reference to each element in a temporary array, then subsequently loop over those, removing each one from the DOM.
问题是我的错;当您从生成的元素数组中删除一个元素时,长度会发生变化,因此每次迭代都会跳过一个元素。解决方案是在一个临时数组中存储对每个元素的引用,然后循环遍历这些元素,从 DOM 中删除每个元素。
回答by Alexander
I prefer using forEach
over for
/while
looping. In order to use it's necessary to convert HTMLCollection
to Array
first:
我更喜欢使用forEach
over for
/ while
looping。为了使用,必须先转换HTMLCollection
为Array
:
Array.from(document.getElementsByClassName("post-text"))
.forEach(element => element.remove());
Pay attention, it's not necessary the most efficient way. Just much more elegant for me.
注意,这不是最有效的方式。对我来说更优雅。
回答by Mohsen
One line
一条线
document.querySelectorAll(".remove").forEach(el => el.remove());
For example you can do in this page to remove userinfo
例如,您可以在此页面中删除用户信息
document.querySelectorAll(".user-info").forEach(el => el.remove());
回答by Can PERK
Recursive function might solve your problem like below
递归函数可能会解决您的问题,如下所示
removeAllByClassName = function (className) {
function findToRemove() {
var sets = document.getElementsByClassName(className);
if (sets.length > 0) {
sets[0].remove();
findToRemove();
}
}
findToRemove();
};
//
removeAllByClassName();
回答by David Tang
Yes, you have to remove from the parent:
是的,您必须从父项中删除:
cur_columns[i].parentNode.removeChild(cur_columns[i]);