使用纯 javascript 查找和删除特定元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18982213/
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
Find and remove specific element using pure javascript
提问by Marc
I have javascript that generates the following HTML
我有生成以下 HTML 的 javascript
<div class='rightbox'>
<div class'testBox'>
</div>
</div>
Now i have a button that when pressed should remove the div whos class is testbox
. Now even though it is in this case it is not always that the testBox
is the first child within the rightbox
.
现在我有一个按钮,按下时应该删除 div whos class is testbox
。现在,即使是在这种情况下,它并不总是在testBox
距离第一个孩子rightbox
。
So how do i find and remove it? and then afterwards test if it is present as a child within the rightbox
?
那么如何找到并删除它呢?然后再测试它是否在rightbox
?
回答by Sirko
Use, e.g., querySelector()
to find your element and then a combination of parentNode
and removeChild()
to delete it.
使用,例如,querySelector()
查找您的元素,然后组合使用parentNode
和removeChild()
删除它。
var el = document.querySelector( '.testBox' );
el.parentNode.removeChild( el );
Edit 2018:
编辑 2018 年:
In the meanwhile support for remove()
has landed (In all browsers, but IE), so the above code can be reduced to the following:
同时remove()
已经支持(In all browsers, but IE),所以上面的代码可以简化为:
document.querySelector( '.testBox' ).remove();
Note, that you should check, whether the selected node actually exists. Otherwiese both snippets will throw an error.
请注意,您应该检查所选节点是否实际存在。否则两个片段都会抛出错误。
回答by Samuli Hakoniemi
var testBoxes = Array.prototype.slice.call(document.querySelectorAll('.testBox'));
testBoxes.forEach(function(testBox) {
testBox.parentNode.removeChild(testBox);
});
回答by Tom
var els = document.getElementsByTagName("div");
var el;
for(var i = 0, ceiling = els.length; i < ceiling; i++) {
el = els[i];
if(el.className == "testbox") {
el.parentNode.removeChild(el);
break;
}
}
var presentAsChildWithinRightbox = false;
for(var i = 0, ceiling = els.length; i < ceiling; i++) {
el = els[i];
if(el.className == "rightbox") {
var childNodes = el.childNodes;
for(var j = 0, ceiling2 = childNodes.length; j < ceiling2; j++) {
if(childNodes[j].className == "testbox") {
presentAsChildWithinRightbox = true;
j = ceiling2;
i = ceiling;
}
}
}
}
if(presentAsChildWithinRightbox)
alert("A div with classname childbox has a child div with classname testbox");
else
alert("A div with classname childbox does not have a child div with classname testbox");
回答by Ganesh Pandhere
Try this
试试这个
$(".rightBox").find("div").eq(0).remove();
$(".rightBox").find("div.testBox").remove();
Note: This is implemented using jQuery
注意:这是使用jQuery实现的