当我加载我的页面时,会创建一个nodeList,它看起来像这样:
[text, h4, text, span, br, input, br, span, br, input, br, span, br, input, br, span, br, input, br]我创建了一个简单的for循环,循环遍历所有这些元素,并从DOM中删除它们中的每一个。 (所有的元素都在<section> )
这是循环:
for(element in videoTitlesElement.childNodes){ if(!isNaN(element)){ videoTitlesElement.removeChild( videoTitlesElement.childNodes[element]); } }但是,在循环结束时,nodeList看起来像这样:
[h4, span, input, span, input, span, input, span, input]并非所有元素都被删除了。 为什么?
谢谢。
When I load my page, a nodeList gets created, and it looks like this:
[text, h4, text, span, br, input, br, span, br, input, br, span, br, input, br, span, br, input, br]I created a simple for loop that loops through all these elements and deletes each one of them from the DOM. (all the elements are in a <section>)
Here's the loop:
for(element in videoTitlesElement.childNodes){ if(!isNaN(element)){ videoTitlesElement.removeChild( videoTitlesElement.childNodes[element]); } }But, by the end of the loop, the nodeList looks like this:
[h4, span, input, span, input, span, input, span, input]not all elements got removed. Why?
Thanks.
最满意答案
两件事情。 首先,在迭代数字索引时不要使用for ... in ; 使用普通的for循环。 那么你不会需要isNaN()检查,而且它通常更安全。
第二个问题是,当你删除一个孩子时,你改变了列表的长度。 如果您删除了0号孩子,那么曾经是孩子1的孩子会变成孩子0.因此,您真正想要的只是一个简单的while循环:
while (videoTitlesElement.childNodes.length) videoTitlesElement.removeChild(videoTitlesElement.childNodes[0]);或者更简单:
while (videoTitlesElement.firstChild) videoTitlesElement.removeChild(videoTitlesElement.firstChild);我还应该注意(假设你正在使用HTML DOM),通过简单地通过.innerHTML爆破,更容易清除元素的所有子节点:
videoTitlesElement.innerHTML = "";Two things. First, don't use for ... in when you're iterating through numeric indexes; use a plain for loop. Then you won't need that isNaN() check, and it's generally safer.
The second problem is that when you remove a child, you change the length of the list. If you remove child 0, then the child that used to be child 1 becomes child 0. Thus, what you really want is a simple while loop:
while (videoTitlesElement.childNodes.length) videoTitlesElement.removeChild(videoTitlesElement.childNodes[0]);or, simpler:
while (videoTitlesElement.firstChild) videoTitlesElement.removeChild(videoTitlesElement.firstChild);I should also note (assuming you're working with an HTML DOM) that it's easier to clear out all the child nodes of an element by simply blasting it via .innerHTML:
videoTitlesElement.innerHTML = "";更多推荐
发布评论