Home > Net >  How do I change multiple elements with the same class to a list of array items
How do I change multiple elements with the same class to a list of array items

Time:10-30

Basically, I have multiple elements with the same class name, what I am doing is fetching an array of integers from an API, I want to loop through all the elements with this class name and change each one to one of the elements from the array in order. For example

<p class="test">hello</p>
<p class="test">hello</p>
<p class="test">hello</p>
<p class="test">hello</p>

and the array looks like this [1,5,2,11] after the loop, things should look like this

<p class="test">1</p>
<p class="test">5</p>
<p class="test">2</p>
<p class="test">11</p>

Thank you)

CodePudding user response:

Loop through the array indexes. Then use that index to access the corresponding array elements and DOM elements.

const array = [1, 5, 2, 11];
const paras = document.getElementsByClassName("test");

array.forEach((val, i) => paras[i].innerText = val;
  • Related