DEV Community

_Khojiakbar_
_Khojiakbar_

Posted on

Dynamically Adding To The Webpage

The code iterates through an array called userList, and for each user object (el), it creates a card element using the createElement function. This card contains the user's avatar, name, and email. The card is then appended to an element called servicesContent.


// Iterate through each user object in the userList array
userList.forEach(el => {
    // Create a 'card' div with user details using the createElement function
    const card = createElement('div', 'card', `
        <img src="${el.avatar}" alt="img" class="w-3">
        <div class="p-2">
            <h1>${el.last_name} ${el.first_name}</h1>
            <p>${el.email}</p>
        </div>
    `);

    // Append the created card to the servicesContent element
    servicesContent.append(card);
});
Enter fullscreen mode Exit fullscreen mode

Detailed Steps

  1. Iterate through userList: The forEach method loops through each user object (el) in the userList array.
  2. Create a Card: For each user object, a div element with the class card is created. This card contains:
  3. An img element displaying the user's avatar.
  4. A div with the user's name and email.
  5. Append the Card: The created card is appended to the servicesContent element.

Key Points

createElement Function: This is used to create the card element. It takes three arguments: the tag name ('div'), the class list ('card'), and the inner HTML content (a template literal containing the user's details).

Template Literals: Template literals (enclosed in backticks `) allow embedding variables directly into the string using${variable}` syntax.

Appending to the DOM: The append method adds the created card element to the servicesContent element in the DOM.


This code dynamically creates and adds a user card to the webpage for each user in the userList array.

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay