1

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!

5
  • What is the current result you are getting? Cause looking at the details in the question, it seems everything should work properly. Commented Apr 3, 2021 at 17:43
  • book is undefined in that for loop that sets the attribute. What errors do you see in dev tools console? Commented Apr 3, 2021 at 17:48
  • According to your code, since the books are stored in myLibrary, you should replace book with myLibrary[i] in the loop. Or use the forEach loop like you did with addedBooks Commented Apr 3, 2021 at 17:50
  • Or use the same for of as you did previously Commented Apr 3, 2021 at 17:50
  • use book.dataset.index = i Commented Apr 3, 2021 at 17:53

2 Answers 2

3

const books = document.querySelectorAll('.bookStyle')
books.forEach((book, i) => book.setAttribute('data-index', i))
<div class='bookStyle'> Title of book</div>
<div class='bookStyle'> Title of book</div>
<div class='bookStyle'> Title of book</div>
<div class='bookStyle'> Title of book</div>

Sign up to request clarification or add additional context in comments.

Comments

0

Thanks for all the replies, this worked for me:

const books = document.querySelectorAll('.bookStyle') books.forEach((book, i) => book.setAttribute('data-index', i))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.