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>
Simply you can use map, but map
is return new Array.
After that using join
to return string.
const ct = document.querySelector('.ct');
const data = ['123', '456', '789'];
const createNewElement =
'<p>' +
data.map((elm) => '<a>' + elm + '</a>').join('') +
'</p>';
ct.insertAdjacentHTML('beforeend', createNewElement);
Using all what you used and just using appendChild
this one is easiest solution.
let ct = document.querySelector(".ct");
const arr = [100,102,900];
arr.forEach(value=>{
const currentElement = document.createElement("a");
currentElement.innerHTML = value + "<br/>";
ct.appendChild(currentElement);
})
<p class="ct"></p>
another way of doing is making a string of html and just inserting it into element where you want those elements
let ct = document.querySelector(".ct");
const arr = [100,102,900];
let fullHTML = "";
arr.forEach(value=>{
fullHTML += "<p>"+value+"</p>";
})
ct.innerHTML = fullHTML;
<div class="ct"></div>
Links for learning more about this
You need to use Array.prototype.map
instead of forEach
, the map
method of an array returns a new array, allowing you to save it inside the createNewElement
constant, while the forEach
method on an array runs something on each element inside the array without returning a new array.
the .join('')
method used at the end is to convert the array (createNewElement
) into a string, joining each element in the array by no delimiters, (the default delimiter is the comma ,
).
Read more about Array.prototype.map() method here
const ct = document.querySelector('.ct');
const data = ['123', '456', '789'];
const createNewElement = data.map((elm) => '<p><a>' + elm + '</a></p>')
console.log(createNewElement)
ct.insertAdjacentHTML('beforeend', createNewElement.join(''));
<div class="ct"></div>