问题
<!DOCTYPE html>
<meta charset="utf-8">
<title>An HTML5 Document</title>
<p>1
<p>2
<p>3
<p>4
<p>5
<p>6
<p>7
<p>8
<p>9
<p>10
<p>11
<p>12
<script>
// When the document is clicked, codes below should remove all the paragraphs in the page.
// There are 12 paragraphs in the page, but codes below can just remove 6 of them.
document.addEventListener('click', function () {
var i, allParagraphElements = document.getElementsByTagName('p');
console.log('allParagraphElements.length: ' + allParagraphElements.length);
for (i = 0; i < allParagraphElements.length; i += 1) {
console.log('i: ' + i);
allParagraphElements[i].parentNode.removeChild(allParagraphElements[i]);
}
}, false);
</script>
See codes on jsFiddle: http://jsfiddle.net/7NmRh
How can I fix this problem? Thank you.
回答1:
You iterate from top to bottom:
Iteration one: twelve paragraphs, index = 0
paragraph at index 0 is deleted and paragraph 1 is now at index 0
Second iteration: Eleven paragraphs, index = 1
paragraph at index 1 is deleted and paragraph 2 is now at index 1
You see what's going wrong? You only delete half of the paragraphs
Iterate the other way around and all the paragraphs are deleted
JSFIDDLE
回答2:
.getElementsByTagName
returns a live nodelist which is automatically updated as you make changes to the underlying subtree it represents. Basically, when you remove elements the .length
is changed as well and the loop will end "prematurely".
You could use .querySelectorAll
to get a static nodelist instead.
http://jsfiddle.net/7NmRh/1/
allParagraphElements = document.querySelectorAll('p');
You can also convert the nodelist to an array, which behaves like a static nodelist as well:
allParagraphElements = [].slice.call( document.getElementsByTagName('p') );
http://jsfiddle.net/7NmRh/4/
来源:https://stackoverflow.com/questions/11722760/i-cant-remove-all-the-paragraphs-in-the-page-via-javascript