Search code examples
javascripthtmlfor-loopjavascript-objectsnested-for-loop

How do I iterate through an object and assign the values (colors) to each div being created


I am trying to use the data object which I have created to then output the name into a html div, and then styling that text to be the color which is also stored in the data. I have managed to output the text into the divs, however I would prefer to add classnames. And it seems to just add the red to every single div, which is not what I was looking for.

So the desired output would be:

halfords red text microsoft green text posca blue text

I would really appreciate the help, bit of a noob over here!

const container = document.querySelector("#slider-container");

const data = [
  { name: "halfords", color: "red", logo: "" },
  { name: "microsoft", color: "green", logo: "" },
  { name: "posca", color: "blue", logo: "" }
];

// Iterate through object and adding colours to <div>'s
var divs = document.querySelectorAll("div");
for (const iterator of data) {
  for (let i = 0; i < divs.length; ++i) {
    divs[i].style.color = data[i].color;
  }
}

// Iterating through object and outputting into <div>'s
function createMenuItem(name) {
  let div = document.createElement("div");
  div.textContent = name;
  return div;
}

document.addEventListener("DOMContentLoaded", function () {
  for (let i = 0; i < data.length; i++) {
    container.appendChild(createMenuItem(data[i].name));
  }
});
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Slider</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    
    <div id="slider-container"></div>

</body>
</html>


Solution

  • Just some suggestions, you don't need to loop over data. Also, it seems you are selecting all divs, including slide-container. You could add a class to your divs inside createMenuItem instead, and then select only them. Here's how you can do it.

    const container = document.querySelector("#slider-container");
    
    const data = [
      { name: "halfords", color: "red", logo: "" },
      { name: "microsoft", color: "green", logo: "" },
      { name: "posca", color: "blue", logo: "" },
    ];
    
    // Iterate through object and adding colours to <div>'s
    
    // Iterating through object and outputting into <div>'s
    function createMenuItem(name) {
      let div = document.createElement("div");
      div.textContent = name;
      div.classList.add("item");
      return div;
    }
    
    document.addEventListener("DOMContentLoaded", function () {
      for (let i = 0; i < data.length; i++) {
        container.appendChild(createMenuItem(data[i].name));
      }
    
      var divs = document.querySelectorAll(".item");
    
      for (let i = 0; i < divs.length; ++i) {
        divs[i].style.color = data[i].color;
      }
    });