我有一个将“div”子节点附加到父节点的函数,然后我需要使用 removeChild() 方法删除这个子节点,但它不起作用。
这是我的代码:
function ColorCards()
{for (i=0; i<numerocaselle; i++)
{document.getElementsByClassName("MemoryCards")[i].style.border="none"
var esempiocolore=document.createElement('div')
esempiocolore.style="position: relative; height: 80px; width: 130px; background-image: url('img/backcard"+cartaesempio+".png'); background-size: cover;"
document.getElementsByClassName("MemoryCards")[i].appendChild(esempiocolore)
}
}
function CleanColorCards()
{for (i=0; i<numerocaselle; i++)
{document.getElementsByClassName("MemoryCards")[i].style.border="dashed 3px #02A494"
document.getElementsByClassName("MemoryCards")[i].removeChild(document.getElementsByTagName("div"))
}
}
有人对如何让它发挥作用有什么建议吗?
最佳答案
您正在将 NodeList 传递给 removeChild
,而您应该传递单个节点。其次,document.getElementsByTagName("div")
还将查找不是您要从中移除子项的父项的子项的元素。
那么这样做:
// Avoid repetition of code, and store the result in a variable:
var nodelist = document.getElementsByClassName("MemoryCards");
for (var i=0; i<numerocaselle; i++){
const parent = nodelist[i];
parent.style.border="dashed 3px #02A494";
// Perform `getElementsByTagName` on the parent node only, and take first match:
parent.removeChild(parent.getElementsByTagName("div")[0]);
}
请注意,querySelector
是为获取一个节点结果而设计的,因此最后一行可以是:
parent.removeChild(parent.querySelector("div"));
关于javascript - 正确使用 removeChild(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55995765/