How can I add HTML class when for loop in JavaScript

Issue

I am trying to add a class when looping through an array, here is my current code:

var users = [{
    name: "Jan",
    id: "1",
    number: "111-111-111"
  },
  {
    name: "Juan",
    id: "2",
    number: "222-222-222"
  },
  {
    name: "Margie",
    id: "3",
    number: "333-333-333"
  },
  {
    name: "Sara",
    id: "4",
    number: "444-444-444"
  },
  {
    name: "Tyrell",
    id: "5",
    number: "555-555-555"
  },
];

var div = "<div>";
for (var i = 0; i < users.length; i++) {
  div += "<p>" + users[i].name + "</p>";
  div += "<p>" + users[i].id + "</p>";
  div += "<p>" + users[i].number + "</p>";
}
div += "</div>";
document.getElementById("usersList").innerHTML = div;
<div class="contact-container">
  <div class="navbar">
    <ul>
      <li>
        <img src="https://img.icons8.com/ios-filled/50/000000/contact-card.png" />
      </li>
      <li>
        <a href="#">View</a>
      </li>
      <li>
        <a href="#">Add</a>
      </li>
      ...
    </ul>
  </div>
  <div class="users" id="usersList">

  </div>

Is there any way I can add a class when looping?

Solution

Why don’t you put a class right there while looping?
like this

for (var i = 0; i < users.length; i++) {
  div += "<p class='myclass'>" + users[i].name + "</p>";
  div += "<p class='myclass'>" + users[i].id + "</p>";
  div += "<p class='myclass'>" + users[i].number + "</p>";
}

Answered By – Omid_Mirzaee_Yazdi

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published