Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

224
Vistas
is there a way to assign id or classname to an element through document.createElement?

Im still relatively new to JS. I know i probably shouldnt write my code the way i have done here in the real world, but im only doing this to test my knowledge on for loops and pulling JSON data.

My question is, with the way i have structured my code, is it possible for me to add classnames/Id's to the elements i have made using doc.createElement? for example if i wanted to add custom icons or buttons to each element? I cant seem to think of a way to add them other than having to write out all the HTML and do it that way. Here's my code :

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="./styles.css">
    <title>Document</title>
</head>
<body>
    <section>
    </section>
    <script src="./app.js"></script>
</body>
</html>

JS

const allCustomers = document.querySelector("section");

let custName = "";
let username = "";
let email = "";
let id = "";

const requestURL = "https://jsonplaceholder.typicode.com/users";

fetch(requestURL)
  .then((response) => response.text())
  .then((text) => DisplayUserInfo(text));

function DisplayUserInfo(userData) {
  const userArray = JSON.parse(userData);

  for (i = 0; i < userArray.length; i++) {
    let listContainer = document.createElement("div");
    let myList = document.createElement("p");
    let myListItems = document.createElement("span");
    myList.textContent = `Customer : ${userArray[i].name}`;
    myListItems.innerHTML =`<br>ID: ${userArray[i].id} <br>Email: ${userArray[i].email} <br>Username: ${userArray[i].username}`; 
    myListItems.appendChild(myList);
    listContainer.appendChild(myListItems);
    allCustomers.appendChild(listContainer);
  }
}

DisplayUserInfo();

Any pointers would be greatly appreciated as well as any constructive feedback. Thanks

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Yes, for sure you can add any attribute for a created element. element.classList.add('class-name-here') for adding class, element.id = 'id-name-here' for adding id.

const allCustomers = document.querySelector("section");

let custName = "";
let username = "";
let email = "";
let id = "";

const requestURL = "https://jsonplaceholder.typicode.com/users";

fetch(requestURL)
  .then((response) => response.text())
  .then((text) => DisplayUserInfo(text));

function DisplayUserInfo(userData) {
  const userArray = JSON.parse(userData);

  for (i = 0; i < userArray.length; i++) {
    let listContainer = document.createElement("div");
    let myList = document.createElement("p");
    myList.classList.add('active');
    myList.id = 'paragraph'
    let myListItems = document.createElement("span");
    myList.textContent = `Customer : ${userArray[i].name}`;
    myListItems.innerHTML =`<br>ID: ${userArray[i].id} <br>Email: ${userArray[i].email} <br>Username: ${userArray[i].username}`; 
    myListItems.appendChild(myList);
    listContainer.appendChild(myListItems);
    allCustomers.appendChild(listContainer);
  }
}

DisplayUserInfo();
.active {
  color: red;
}

#paragraph {
  font-size: 24px;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="./styles.css">
    <title>Document</title>
</head>
<body>
    <section>
    </section>
    <script src="./app.js"></script>
</body>
</html>

about 4 years ago · Juan Pablo Isaza Denunciar

0

is it possible for me to add classnames/Id's to the elements i have made using doc.createElement

Yes possible with classList for adding class and setAttribute to add id

let listContainer = document.createElement("div");
// To add class
listContainer.className = 'your-class'; //if you have just one
listContainer.classList.add("my-class");//if you want to add multiple
// To add id
listContainer.setAttribute("id", "your_id");
about 4 years ago · Juan Pablo Isaza Denunciar

0

When you use document.createElement it returns an Element. You can use Element attributes and methods to reach what you need. There are some docs for this class on MDN.

This means you can:

> myDiv = document.createElement("div")
<div></div>
> myDiv.id = "test"
'test'
> myDiv
<div id="test"></div>

For classes you can use the attributes className or classList.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda