Search code examples
domiterationaddeventlistenerremovechildgetelementsbytagname

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


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


Solution

  • 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