Removing HTMLCollection elements from the DOM

前端 未结 5 1066
孤独总比滥情好
孤独总比滥情好 2020-11-28 12:53

I have a collection of paragraph elements. Some are empty and some contain whitespace only, while others have content:

Pellentesque habitant morbi t

5条回答
  •  旧时难觅i
    2020-11-28 13:14

    You have to use removeChildon it's parent to do that :

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

    EDIT : plnkr doesn't seems to run well from here, so I haven't tested, but it should work :

    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
    });
    

提交回复
热议问题