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

141
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 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