1

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>

3
  • What exactly isn't working? Is your script running before the DOM is loaded? forEach() doesn't return anything; maybe try map(). Also, your <p> tags are outside your loop, so you'll only get one, not one for each value in the array. Commented May 26, 2022 at 15:22
  • Use map and join them: data.map((elm) => '<a>' + elm + '</a>').join(''). forEach will not modify the array or print anything. Commented May 26, 2022 at 15:23
  • elm is also within your string, so it'll literally print elm, not the array value. Commented May 26, 2022 at 15:25

5 Answers 5

2

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);
Sign up to request clarification or add additional context in comments.

1 Comment

You may want to add some links to MDN documentation for map and insertAdjacentHTML.
1

with just appendChild and createElement

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>

without any createElement but just with innerHTML

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

Comments

0

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>

Comments

0

Another alternative is accumulate in the createNewElement all sub-elements. For this, you can use the .reduce method:

const ct = document.querySelector('.ct');
const data = ['123', '456', '789'];
const createNewElement = data.reduce((allElements, elm) => allElements + '<p><a>' + elm + '</a></p>')

ct.insertAdjacentHTML('beforeend', createNewElement);

Comments

0

You can simply use this to iterate over the array

<div class="ct"></div>

 <script>
        const ct = document.querySelector('.ct');
        const data = ['123', '456', '789'];
        let createNewElement = "";

        for (let k = 0; k < data.length; k++) {

            createNewElement += '<p> <a>' + data[k] + ' </a> </p>';
        }

        ct.insertAdjacentHTML('beforeend', createNewElement);
 </script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.