DEV Community

Michael Fazekas
Michael Fazekas

Posted on

How to display DOM elements with ForEach()

So I'm digging into ForEach() using JS and decided to make a quick way to display your Array index to the DOM in JavaScript.
*side note I already have a blank UL created in my html like this you'll need this at the end of you forEach method.
`


ForEach

<ul>

</ul>
<script src="app.js"></script>
Enter fullscreen mode Exit fullscreen mode

`
first you want to create an Array

const todos = [
    "clean room",
    "study JS",
    "work out",
    "eat healthy"
];
Enter fullscreen mode Exit fullscreen mode

create your forEach() method forEach takes in todos like this (I like using arrow functions btw) and pass in your argument todo:

todos.forEach((todo)=>{
// do something here
})
Enter fullscreen mode Exit fullscreen mode

start creating your elements and classNames inside of the forEach function.

todos.forEach((todo)=>{
    const li = document.createElement("li");
   const liText = document.createElement("span");
   let newDiv = document.createElement("div");`



    li.className = "list";
   liText.className = "items";


 liText.innerHTML = todo;


   li.appendChild(liText);


   newDiv.appendChild(li);


document.querySelector("ul").appendChild(li);

})

Enter fullscreen mode Exit fullscreen mode

Top comments (0)