Skip to main content

JavaScript - Array forEach loop

script.js

// get the html objects
const divText = document.getElementById("divText");

// initialize an array of string values
const colors = ["Red", "Green", "Yellow", "Black"];


// function for button click
function showColors(){
    divText.innerHTML = "";

    // for each loop through the array elements
    colors.forEach( item =>
            divText.innerHTML += item + "<br/>"
    )
}
index.html

<html>
  <head>
    <meta charset="UTF-8" />
    <script src="script.js" defer></script>
    <link rel="stylesheet" type="text/css" href="styles.css" />
  </head>

  <body>
    <div id="divContent">
      <h1>JavaScript : Array forEach loop</h1>
      <button onclick="showColors()">Loop Colors</button>
      <div id="divText"></div>
    </div>
  </body>
</html>
styles.css

@import url("https://fonts.googleapis.com/css2?family=Raleway&display=swap");

body {
  background: #FFF;
  padding: 50px;
  font-family: "Raleway", sans-serif;
}

h1 {
  margin-bottom: 20px;
  background-color: #F0FFFF;
  padding: 25px;
}

button {
  background-color: #3C69E7;
  border: none;
  border-radius: 10px;
  color: white;
  padding: 20px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  margin: 4px 2px;
  outline: none;
}

#divContent {
  width: 700px;
  margin: auto;
  padding-bottom: 250px;
  background-color: #FEFEFA;
  text-align: center;
  display: block;
}

#divText {
 font-size: 40px; 
}
More JavaScript tutorials