Home > Software engineering >  How to introduce each element of an array into existing divs, by order?
How to introduce each element of an array into existing divs, by order?

Time:10-27

Let's say I have one array with 4 elements and also 4 divs.

array = [a, b, c, d]
<div ></div>
<div ></div>
<div ></div>
<div ></div>

How do I insert the "a" from the array into the first div, then the "b" into the second div and so on and so on.

This is what I expect to have:

<div >a</div>
<div >b</div>
<div >c</div>
<div >d</div>

CodePudding user response:

This is the way by which you can achieve this requirement.

const divArray = ['div1', 'div2', 'div3', 'div4'];
const arr = ['a', 'b', 'c', 'd'];

divArray.forEach((item, index) => {
   let divEl = document.createElement('div');
   divEl.className = "lorem-ipsum";
   divEl.innerHTML = arr[index];
   document.getElementById('result').appendChild(divEl);
})
<div id="result"></div>

CodePudding user response:

This would be one way of doing it:

const data = ["a", "b", "c", "d"];

let a=data.slice(0);
document.querySelectorAll(".lorem-ipsum").forEach(div=>div.textContent=a.shift())
<div ></div>
<div ></div>
<div ></div>
<div ></div>

  • Related