How do I create HTML elements dynamically from an array?
For example, if I got an array const data = ['123', '456', '789'] , and I wanna create a p tag of HTML for each value of the array. I've tried to use the foreach method but it's not working, anything I do it wrong so far? Below is the code:
const ct = document.querySelector('.ct');
const data = ['123', '456', '789'];
const createNewElement =
'<p>' +
data.forEach((elm) => '<a>elm</a>') +
'</p>';
ct.insertAdjacentHTML('beforeend', createNewElement);
<div class="ct"></div>
forEach()doesn't return anything; maybe trymap(). Also, your<p>tags are outside your loop, so you'll only get one, not one for each value in the array.mapand join them:data.map((elm) => '<a>' + elm + '</a>').join('').forEachwill not modify the array or print anything.elmis also within your string, so it'll literally printelm, not the array value.