当我运行下面的代码时,一半的项目被从列表中删除..我试图从列表中删除所有项目。removeChild();不从列表中删除所有项目
//Sets an event listener to the reset button.
resetButton.addEventListener('click', (e) => {
const ul = document.getElementById("myUL");
console.log(ul.children.length);
//Moves through the unordered list and removes each list item.
for(let i = 0; i < ul.children.length; i++) {
ul.removeChild(ul.children[i]);
}
});
的[使用Javascript不消除所有可能的复制在一个div中的元素](https://stackoverflow.com/questions/18410450/javascript-not-removing-all-elements-within-a-div) – Xufox
你正在修改你正在迭代的列表 - 这导致了观察到问题。有关解决方案,请参阅https://stackoverflow.com/questions/3955229/remove-all-child-elements-of-a-dom-node-in-javascript。 –
你试过了吗(让我= ul.children.length; i> = 0; i ++)'? – Vivick