我有一个将"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"))
}
}有没有人对如何让它工作有什么建议?
发布于 2019-05-06 03:54:20
您正在向removeChild传递一个NodeList,而您应该传递单个节点。其次,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"));发布于 2019-05-12 06:00:58
只有几个注意事项:
不需要使用for循环的
.MemoryCards长度的计数,就会留下出错的空间。相反,我推荐一个像.forEach()这样的数组函数来迭代你的元素。.MemoryCards更快,因为为什么这种方法是最好的。
let cartaesempio = 10;
ColorCards = () =>
Array.from(document.getElementsByClassName("MemoryCards"))
.forEach(e => {
e.classList.add('borderNone');
let esempiocolore = document.createElement('div');
esempiocolore.style.backgroundImage = `url('https://cdn.dribbble.com/users/285803/screenshots/1066705/dribbble.gif')`;
e.appendChild(esempiocolore);
});
CleanColorCards = () =>
Array.from(document.getElementsByClassName("MemoryCards"))
.forEach(e => {
e.classList.add('boderDashed');
while (e.firstChild) {
e.removeChild(e.firstChild);
}
});
ColorCards();
CleanColorCards();/* Children of the .MemoryCards nodes */
.MemoryCards div {
position: relative;
height: 80px;
width: 130px;
background-size: cover;
}
.borderNone {
border: none;
}
.boderDashed {
border: dashed 3px #02A494;
}<div class='MemoryCards'></div>
希望这能帮上忙
发布于 2019-05-06 03:53:15
getElementsByTagName返回节点列表(数组)。您必须选择一个节点。也许下面这样的代码会对您有用:document.getElementsByTagName("div")[0]
https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName
https://stackoverflow.com/questions/55995765
复制相似问题