Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

223
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda