Removing HTMLCollection elements from the DOM

I have a set of paragraph elements. Some of them are empty, and some contain only spaces, while others have content:

<p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>
<p></p>
<p> </p>
<p>    </p>
<p>&nbsp;</p>
<p> &nbsp;</p>

I use getElementsByTagNameto select them:

var paragraphs = document.getElementsByTagName('p');

This returns all paragraphs in the document. I want to delete all of them, so I would like to run

for (var i = 0, len = paragraphs.length; i < len; i++) {
   paragraphs[i].remove();
}

but I get errors Uncaught TypeError: Cannot read property 'remove' of undefined. I think this is strange, but I will try to add a guard and see what happens:

for (var i = 0, len = paragraphs.length; i < len; i++) {
   paragraphs[i] && paragraphs[i].remove();
}

Error, but not all items are deleted. So I run it again, and it deletes some items that have not been deleted before. I run it again and finally all paragraphs are removed from the document.

I wonder what obvious details I'm missing here.

Problem demonstration

+4
4

, paragraphs . p, . , :

for (var i = paragraphs.length; i--; ) {
   paragraphs[i].remove();
}

() . :

  • var paragraphs =
      Array.prototype.slice.call(document.getElementsByTagName('p'), 0);
    
  • document.querySelectorAll, ( live!):

    var paragraphs = document.querySelectorAll('p');
    

, .remove - DOM . . MDN.


, , node paras = [p0, p1, p2]. , :

i = 0, length = 3, paras[0] == p0  => paras = [p1, p2]
i = 1, length = 2, paras[1] == p2  => paras = [p1]
i = 2, length = 1, END

, p1 , .

+15

HTMLCollection . - while

while(paragraphs.length > 0) {
   paragraphs[0].remove();
}
+6

removeChild :

for (var i = 0, len = paragraphs.length; i < len; i++) {
    paragraphs[i].parentNode.removeChild(paragraphs[i]);
}

EDIT: plnkr, , , , :

window.addEventListener("load", function() {
    var paragraphs = document.getElementsByTagName('p');

    var loop = function() {
        for (var i = 0, len = paragraphs.length; i < len; i++) {
            paragraphs[i].parentNode.removeChild(paragraphs[i]);
        }
    };

    console.log(paragraphs.length) // 7
    loop();
    console.log(paragraphs.length) // 3
    loop();
    console.log(paragraphs.length) // 1
    loop();
    console.log(paragraphs.length) // 0
});
0

:

var temp = document.getElementsByClassName('level-size');
for (var i = 0, len = temp.length; i < len; i++)
    temp[0].remove();

temp [0] , because every time I delete it, the hole table is discarded by one index.

0
source

Source: https://habr.com/ru/post/1542882/


All Articles