There is an array with values, it is necessary to bypass the dom tree and fill the contents of elements with the child-elem class with elements from the array. It turns out that the last element of the array is added to all links. Tell me what I'm doing wrong.

<div class="container"> <div class="parent-elem"> <a class="child-elem"></a> </div> <div class="parent-elem"> <a class="child-elem"></a> </div> <div class="parent-elem"> <a class="child-elem"></a> </div> 

 let arr = [1,2,3]; let div = '.child-elem', elems = document.querySelectorAll(div), elem, key; for (key in elems) { elem = elems[key]; for (let i = 0; i<arr.length; i++) { elem.innerHTML = arr[i] } } 
  • Well, in the nested for loop, you first write to link 1, then erase the old value and write 2, then erase again and write 3 there too - amalmal

2 answers 2

In general, this is solved in one cycle. but there are questions about what to do if there are more house elements than elements in the array? or vice versa and so it is done something like this

 let arr = [1,2,3]; let div = '.child-elem', elems = Array.from(document.querySelectorAll(div)), elem, key; for (let i = 0; i<arr.length; i++) { elems[i].textContent = arr[i] } 
 <div class="container"> <div class="parent-elem"> <a class="child-elem"></a> </div> <div class="parent-elem"> <a class="child-elem"></a> </div> <div class="parent-elem"> <a class="child-elem"></a> </div> 

in your case, the inner loop sequentially writes all the values ​​of the array into the same element and then moves on to the next one. so it turns out that always the last value in all elements.

  • Thanks for helping me figure it out! - Fidel.Marti

It turns out that the last element of the array is added to all links.

You overwrite the values.

 let arr = [1, 2, 3]; let div = '.child-elem', elems = document.querySelectorAll(div), key; i = 0 for (key in elems) { // Добавит цифкру в child-elem elems[key].innerHTML = arr[i++] || 'empty' // при разной длине массивов будет печатать empty } 
 <div class="container"> <div class="parent-elem"> <a class="child-elem"></a> </div> <div class="parent-elem"> <a class="child-elem"></a> </div> <div class="parent-elem"> <a class="child-elem"></a> </div> <div class="parent-elem"> <a class="child-elem"></a> </div> <div class="parent-elem"> <a class="child-elem"></a> </div> </div>