I can't remove all the paragraphs in the page via JavaScript

时光怂恿深爱的人放手 提交于 2019-12-11 11:47:43

问题


<!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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!