What is the best method for including an HTML class within a JavaScript for loop?

Looking for a solution to add a class while iterating through an array? Check out the code snippet below:

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 class='user-item'>" + users[i].name + "</p>";
  div += "<p class='user-item'>" + users[i].id + "</p>";
  div += "<p class='user-item'>" + 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>

Looking to include a class during iteration? Here's a way to achieve that!

Answer №1

Is there a specific reason for not adding a class within the loop like so?

for (let 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>";
}

Answer №2

Simply insert this code snippet into your HTML file

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

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 class='user-name'>" + users[i].name + "</p>";
  div += "<p class='user-id'>" + users[i].id + "</p>";
  div += "<p class='user-number'>" + users[i].number + "</p>";
}
div += "</div>";
document.getElementById("usersList").innerHTML = div;
.user-name {
  color: red;
}

.user-id {
  color: blue;
}

.user-number {
  color: green;
}
<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>

Answer №3

If you want to enhance your code structure, consider constructing your elements in the following manner:

const newDiv = document.createElement("div");
const newP = document.createElement("p");

Next, assign a class name to the paragraph element:

newP.className = "css-style";

Then, append the child elements to their respective parent elements:

newDiv.appendChild(newP);
document.getElementById("userContainer").appendChild(newDiv);

This method is more organized and effective compared to using innerHTML for adding elements.

Answer №4

Even though there is already an accepted answer, I believe this presents a great opportunity to delve into the realm of custom elements for both personal learning and potentially contributing more insights.

Below is the code snippet along with explanatory comments. While it might seem like dark magic to me currently, I am intrigued by the challenge and eager to formulate a comprehensive response:

// Creating a custom element called 'user-card' that will be rendered as <user-card> in the DOM:
customElements.define('user-card',
  class extends HTMLElement {
    constructor() {
      super();
      // Accessing the <template> element using its id and getting its content:
      let template = document.getElementById('user-card');
      let templateContent = template.content;

      // Attaching shadow root and allowing JavaScript modifications:
      const shadowRoot = this.attachShadow({
          mode: 'open'
        })
        .appendChild(templateContent.cloneNode(true));
    }
  }
);

// Data definition:
let 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"
    },
  ],
  userDiv = document.querySelector('#usersList');

// Iterating through the data array using Array.prototype.forEach():
users.forEach(
  (user) => {
    // Creating a new <user-card> and <li> element:
    let card = document.createElement('user-card'),
      li = document.createElement('li'),
      fragment = document.createDocumentFragment();

    // Iterating over Object keys and assigning each key-value pair to a separate div element:
    Object.keys(user).forEach(
      (key) => {
        let clone = li.cloneNode();

        clone.classList.add(key);

        clone.style.setProperty('grid-area', key);

        clone.textContent = user[key];

        fragment.append(clone);
      })

    card.append(fragment);
    userDiv.append(card);
  });
/* Basic CSS reset */
*,
 ::before,
 ::after {
  box-sizing: border-box;
  font-size: 1rem;
  font-family: Calibri, Helvetica, Ubuntu, Arial, sans-serif;
  line-height: 1.4;
  margin: 0;
  padding: 0;
}

.users {
  /* Using Grid display for cards layout */
  display: grid;
  gap: 0.5em;
  grid-template-columns: repeat(auto-fit, minmax(7rem, 1fr));
  margin: 1em auto;
  max-width: 90vw;
}
<template id="user-card">
<style>
  ol {
    border: 1px solid #ccc;
     list-style-type: none;
     display: grid;
     gap: 0.5em;
     grid-template-areas:
       "id name name"
       "number number number";
     padding: 0.25em;
     margin: 0;
  }
</style>
  <ol>
    <slot></slot>
  </ol>
</template>
<div class="contact-container">
  <div class="users" id="usersList"></div>
</div>

Check out the JS Fiddle demo.

Further Reading:

Suggested Readings:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Current polyfill available for requestAnimationFrame

Recently, I read on that requestAnimationFrame in Chrome 20 now has a new sub-millisecond precision timer. It looks like I need to update my code to accommodate this change. After checking out various polyfills, it seems like they were created before thi ...

What is the best way to create grid designs using less in bootstrap?

When using Bootstrap without a preprocessor, we include classes directly into our opening tags like this: <div id="El" class="col-md-1"></div> Personally, I usually work with Bourbon Neat and Sass. With Sass, I can import mixins in the rules ...

The functionality of hover and custom attribute is not operational on IE8

Unfortunately, I am facing issues with the hover and custom attribute functionality in IE8. Even in compatibility mode, it refuses to work properly. The code snippet provided (fiddle) works perfectly fine on Mozilla, Opera, Safari, and Chrome but encounter ...

How can the value be accessed when using getElementById in Angular for <mat-select> elements that do not have a value attribute?

Within a loop, I have an element that has a dynamically generated id: <mat-select multiple class="dw-input" [value]="element.txn_type_id ? element.txn_type_id.split(',') : []" id="field-{{element.Name}}-txn_type_id&quo ...

How ASP.net can dynamically generate URLs in external CSS files

I have been trying to organize my css separately from the *.aspx file. Everything was working fine when the following code was included in the aspx file: background-image: url('<%=Page.ResolveUrl("~/Themes/Red/Images/Contestant/1.jpg)%>';) ...

Network plot search box

I have utilized the forceNetwork() function from the networkD3 package to construct a Network of protein mutations. It is then displayed in RStudio's "Viewer" pane. After creating this network, I am able to save it as an HTML file for sharing while r ...

What is the method for adding a clickable link to an HTML tag in a shiny application?

Looking to jazz up my shiny app, I decided to add a footer using the HTML tag with fluidPage(): tags$footer(HTML(sprintf("For more information, visit www.website.com", align = "center", ...

Troubleshooting: Bootstrap 4 Navbar Not Collapsing

I can't figure out why my code isn't functioning. I attempted to replicate the button and div tags from Bootstrap's website examples, but it seems I may have overlooked something, specifically in the social media icons section. I even tried ...

Displaying angular ng-messages only when the field has been touched

Nothing too out of the ordinary here. I need my input to be validated with each keystroke. If the validation fails, I want the error message to display right away, without waiting for the blur event to trigger the $touched function. I assumed this was th ...

NPM: Handling multiple prehooks with the same name

Is it possible to have multiple prehooks with the same name in my package.json file? For example, having two instances of pretest: "scripts": { "start": "react-scripts start", ... "pretest": "eslin ...

Can a single page be used to send email?

My PHP form is currently sending data to another page, and the layout does not look good. I want to keep the form on the same page so that when a user fills it out, the information is submitted without redirecting. If any of the inputs are empty, I would l ...

Create and adapt dynamic tiles to fit within the available width

I am looking to create a dynamic tile (div) that adjusts based on the number of users available, similar to how it works in Microsoft Teams meetings. For example, if there is only one user, the div should occupy the full screen. When there are two users ...

Having trouble making the jQuery "simulate width: calc(100%)" function work properly?

I am utilizing a combination of HTML, CSS, mediaQuery, Javascript, jQuery, and PrimeFaces in my project. One particular css property I want to use is: calc(100% - 100px) To handle old browsers that do not support this property, I have implemented a javas ...

The $route object in vue-router appears to be empty when used with single file components

I am facing an issue while using single file components with vue-router and vue-2.0. The problem I can't seem to resolve is that the this.$route object, when called from a component, always returns empty values. For example: https://i.sstatic.net/ws ...

Function compilation did not succeed in the module

I've put together a MERN (MongoDB, ExpressJS, React, Node) project using express-generator (express myNewApp). Within a react component, I have implemented this ES6 code snippet: onChange = (event, { newValue }) => { // Line 53 this.setSt ...

How to Use Jquery to Deactivate a Div with a Background Color

Currently, I have a div that contains several child divs. My goal is to disable the parent div and all of its children, showing them in gray color. I initially tried using the CSS property opacity, but unfortunately, the background color didn't change ...

Unlocking the Power of Session Variables in AngularJS using Ui-router

Currently, I am utilizing Angular to manage routes. On the server side, Passport is being used so that I can access the user session variable req.user in my views. However, when dealing with a route rendered by ui-router, my req.user ends up being undefine ...

Achieving fixed width and automatic height for images in Next JS: a guide

I am struggling to showcase a list of images with a fixed width while utilizing the original image height set at 100%. A similar inquiry can be found here, yet it remains unanswered. I have gone through the responses shared here and attempted them. The im ...

Building personalized error messages using graphql-js and express

It has come to my attention that you have the ability to create customized errors within graphql and graphql-express. https://codeburst.io/custom-errors-and-error-reporting-in-graphql-bbd398272aeb I recently implemented a custom Error feature, but it see ...

How can I display a customized component on a table based on the data object's value?

I am working on a custom Table component that I want to render based on an array of objects. The challenge is that I need the Table component to have two props: one for the data object and another for an array of objects, each containing a title and a func ...