loops - JavaScript .children HTML collection length issues when looping -


i'm attempting loop through htmlcollection produced javascript's .children property using following code:

var articles = data.children; var newsgrid = document.getelementbyid('js-news__grid');  (var = 0; < articles.length; i++) {    articles[i].classlist.add('loading');    newsgrid.appendchild(articles[i]); }; 

the data variable fragment of successful xhr. when run loop, appends first child , loop ends, , when running console.log(articles); before loop, shows 2 html elements (like should) has length of 1. if remove loop , run console.log(articles); shows 2 html elements before, has length of 2.

i've left out xhr code sake of simplicity , due fact htmlcollection produced data.children looks correct. here log messages:

[article.news__item, article.news__item] 0: article.news__item 1: article.news__item length: 2 __proto__: htmlcollection  [article.news__item, article.news__item] 0: article.news__item length: 1 __proto__: htmlcollection 

the problem .children live collection, updated move each child out of container.

in case, there 2 children data articles.length 2 when loop started, after first iteration have relocated first child means articles object contains 1 element , i 2 loop condition i < articles.length fails.

so 1 easy solution use reverse loop

var articles = data.children; var newsgrid = document.getelementbyid('js-news__grid');  (var = articles.length - 1; >= 0; i--) {     articles[i].classlist.add('loading');     newsgrid.appendchild(articles[i]); }; 

another solution convert articles normal array

var articles = [].slice.call(data.children); 

another approach suggested robg is

var articles = data.children; var newsgrid = document.getelementbyid('js-news__grid');  while (articles.length) {     articles[0].classlist.add('loading');     newsgrid.appendchild(articles[0]); }; 

Comments