I 'd like to set a data attribute to divs created by looping though an array.
let myLibrary = [ ] //the array
for (const book of myLibrary){
let cover = document.createElement('div')
cover.textContent =`title: ${book.title}`
cover.classList.add('bookStyle') //adding class for css
books.appendChild(cover) //appending to class='books'
}
adding delete buttons to books:
const addedBooks = document.querySelectorAll('.bookStyle')
addedBooks.forEach(book => {
book.addEventListener('click', removeBook)
let del = document.createElement('BUTTON');
del.classList.add('delBtn')
del.textContent = 'x'
book.appendChild(del)
})
I want to do something like this: (looping through childs, adding data-attribute)
for (let i = 0; i < myLibrary.length; i++){
book.setAttribute('data-index', i)
}
in the end, a list of "books" would look like something like this:
<div class = 'bookStlye' data-index: 0> Title of book</div>
<div class = 'bookStlye' data-index: 1> Title of book</div>
<div class = 'bookStlye' data-index: 2> Title of book</div>
<div class = 'bookStlye' data-index: 3> Title of book</div>
Any help appreciated!
bookis undefined in that for loop that sets the attribute. What errors do you see in dev tools console?booksare stored inmyLibrary, you should replacebookwithmyLibrary[i]in the loop. Or use theforEachloop like you did withaddedBooksfor ofas you did previouslybook.dataset.index = i