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> </p>
<p> </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