For ... in loop does not iterate over all properties?

When I load my page, a nodeList node is created and it looks like this:

[text, h4, text, span, br, input, br, span, br, input, br, span, br, input, br, span, br, input, br]

I created a simple loop forthat iterates over all of these elements and removes each of them from the DOM. (all items are in <section>)

Here's the loop:

        for(element in videoTitlesElement.childNodes){
            if(!isNaN(element)){
                videoTitlesElement.removeChild(
                        videoTitlesElement.childNodes[element]);
            }
        }

But, towards the end of the loop, nodeList looks like this:

[h4, span, input, span, input, span, input, span, input]

Not all items are deleted. Why?

Thanks.

+4
source share
3 answers

Two things. First, do not use for ... inwhen you repeat numeric indices; use a simple loop for. Then you do not need a check isNaN(), and it is generally safer.

, . 0, , 1, 0. , while:

while (videoTitlesElement.childNodes.length)
  videoTitlesElement.removeChild(videoTitlesElement.childNodes[0]);

, :

while (videoTitlesElement.firstChild)
  videoTitlesElement.removeChild(videoTitlesElement.firstChild);

( , HTML DOM), , .innerHTML:

videoTitlesElement.innerHTML = "";
+11

(videoTitlesElement.childNodes) . :

var children = [].slice.call(videoTitlesElement.childNodes);

for(element in children){
    if(!isNaN(element)){
         videoTitlesElement.removeChild(videoTitlesElement.childNodes[element]);
    }
}
+4

, , .

for , , , . , , 1 , 0 . , 1, . , .

+3

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


All Articles