从DOM中删除元素 [英] Remove element from DOM
问题描述
我有一个代码:
<ul class='mates'>
<li class='m' id='1'>Jakub</li>
<li class='f' id='2'>Vinnie</li>
<li class='m' id='3'>David</li>
</ul>
此脚本根据用户输入选择li元素之一:
This script selects one of the 'li' elements, according to users input:
<script>
var mates = document.getElementsByClassName('mates')[0];
for (var i=0; i< mates.childNodes.length; i++){
if(mates.children[i].innerHTML == 'Vinnie') alert("Got you! ID "+mates.children[i].id)
}
</script>
我需要删除此元素:
<script>
var mates = document.getElementsByClassName('mates')[0];
for (var i=0; i< mates.childNodes.length; i++){
if(mates.children[i].innerHTML == 'Vinnie') {
alert("Got you! ID "+mates.children[i].id);
parent = document.getElementsByClassName('mates');
mateToDelete = mates.children[i];
parent.removeChild(mateToDelete);
}
}
</script>
这是我以几种不同的方式尝试,但总是有错误,例如不能调用方法'removeChild'未定义。任何想法?
This is what I tried in several different ways but I always got error, e.g. " Cannot call method 'removeChild' of undefined". Any ideas?
推荐答案
您已经从原始的getElementsByClassName中获取了父节点,并且您的孩子通过循环,只是执行了。
You already have the parent node from your original getElementsByClassName, and you have your child through the loop that you've just performed.
因此,很简单:
for (var i=0; i< mates.childNodes.length; i++){
if(mates.children[i].innerHTML == 'Vinnie'){
alert("Got you! ID "+mates.children[i].id)
mates.removeChild(mates.children[i]);
break;
}
}
为了完整起见(并防止进一步争论在评论中:P),如果您实际上可能从列表中删除多个Vinnie,那么最好列出要删除的孩子,然后按照以下方式删除它们:
For the sake of completeness (and to prevent further arguing in comments :P), if you are in fact potentially deleting multiple "Vinnie"'s from your list, then it would be better to make a list of those children you want to delete, then delete them after like so:
var toDelete=[],
i;
for (i=0; i< mates.childNodes.length; i++){
if(mates.children[i].innerHTML == 'Vinnie'){
alert("Got you! ID "+mates.children[i].id)
toDelete.push(mates.children[i]);
}
}
for (i=0; i<toDelete.length; i++){
mates.removeChild(toDelete[i]);
}
这篇关于从DOM中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!