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

147
Visualizações
How to add an ID to every div element created inside a .forEach loop?

I want to create an ID for every booksDisplay div because I want bookOne, bookTwo, bookThree and bookFour to have their own containers. Right now, textNode runs through every div and I want for every div to be seperate. I could have created divs inside HTML but I want to do it dynamically inside javascript.

const booksContainer = document.querySelector('.booksContainer');


const book = {
  title: '',
  author: '',
  pages: '',
  imageUrl: '',
}


const bookOne = {
  imageUrl: '',
  title: 'Title:' + ' ' + 'Armageddon: The Battle for Germany, 1944-1945',
  author: 'Author:' + ' ' + 'Max Hastings',
  pages: 'Pages:' + ' ' + '672'
}
    

const bookTwo = {
  imageUrl: '',
  title: '',
  author: '',
  pages: ''
}


const bookThree = {
  imageUrl: '',
  title: '',
  author: '',
  pages: ''
}


const bookFour = {
  imageUrl: '',
  title: '',
  author: '',
  pages: ''
}
    
let myLibrary = [bookOne, bookTwo, bookThree, bookFour]


myLibrary.forEach((book, index) => {
  let booksDisplay = document.createElement('div')
  booksDisplay.setAttribute('class', 'booksDisplay')
  let booksDisplayText = document.createTextNode(`${bookOne.title}: ${bookOne.author}: ${bookOne.pages}`);
  booksDisplay.appendChild(booksDisplayText)
  booksContainer.appendChild(booksDisplay)

});
<!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/style.css">
    <title>Document</title>
</head>
<body>
<div class="myLibrary">
   <div class="booksContainer">
     
   </div>
    </div>

    
    <script src="./scripts/script.js"></script>
</body>
</html>

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You mean you want the id on the html tag? Why not use the loop you already have and use the index as the id?
Also, no need to create a variable for each book, just put them directly in an array:

const booksContainer = document.getElementById('booksContainer');

const myLibrary = [
  {
    imageUrl: '',
    title: 'Title:' + ' ' + 'Armageddon: The Battle for Germany, 1944-1945',
    author: 'Author:' + ' ' + 'Max Hastings',
    pages: 'Pages:' + ' ' + '672'
  },
  {
    imageUrl: '',
    title: 'book 2',
    author: '',
    pages: ''
  },
  {
    imageUrl: '',
    title: 'book 3',
    author: '',
    pages: ''
  },
  {
    imageUrl: '',
    title: 'book 4',
    author: '',
    pages: ''
  }
];

myLibrary.forEach((book, index) => {
  let booksDisplay = document.createElement('div');
  booksDisplay.setAttribute('class', 'booksDisplay')
  booksDisplay.setAttribute('id', `booksDisplay${index + 1}`);

  let booksDisplayText = document.createTextNode(`${book.title}: ${book.author}: ${book.pages}`);
  booksDisplay.appendChild(booksDisplayText);
  booksContainer.appendChild(booksDisplay);
});
about 4 years ago · Juan Pablo Isaza Relatório

0

Create var counter = 0; outside of your forEach.

Then, you have to add only one line of code - console.log(booksDisplay.id = 'customId' + (++counter)).

Note: console.log is there just for clarification.

const booksContainer = document.querySelector('.booksContainer');


const book = {
  title: '',
  author: '',
  pages: '',
  imageUrl: '',
}


const bookOne = {
  imageUrl: '',
  title: 'Title:' + ' ' + 'Armageddon: The Battle for Germany, 1944-1945',
  author: 'Author:' + ' ' + 'Max Hastings',
  pages: 'Pages:' + ' ' + '672'
}

const bookTwo = {
  imageUrl: '',
  title: '',
  author: '',
  pages: ''
}


const bookThree = {
  imageUrl: '',
  title: '',
  author: '',
  pages: ''
}


const bookFour = {
  imageUrl: '',
  title: '',
  author: '',
  pages: ''
}
    
let myLibrary = [bookOne, bookTwo, bookThree, bookFour]

var counter = 0;
myLibrary.forEach((book, index) => {
  let booksDisplay = document.createElement("div")
  booksDisplay.setAttribute('class', 'booksDisplay')
  console.log(booksDisplay.id = 'customId' + (++counter))
  let booksDisplayText = document.createTextNode(`${bookOne.title}: ${bookOne.author}: ${bookOne.pages}`);
  booksDisplay.appendChild(booksDisplayText)
  booksContainer.appendChild(booksDisplay)
});
<!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/style.css">
    <title>Document</title>
</head>
<body>
<div class="myLibrary">
   <div class="booksContainer">
     
   </div>
    </div>

    
    <script src="./scripts/script.js"></script>
</body>
</html>

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