Javascript Library Project


#1

Happy Saturday everyone,
My question regards the ‘delete’ button part of the Library project, which stumped me for a bit. The project instructions recommend using data attributes to reference created DOM elements but I couldn’t figure out how to get that to work and couldn’t find any good online resources demonstrating using data attributes in a real world example (as in anything but console.log). I ended up adding event listeners to each created element with a splice function and it works, but I’ve seen online resources saying not to add event listeners to elements dynamically created in loops.

I’ve included my code below and my question is if there is anything problematic with it or if there is a better way of doing the delete button part? Also, if you know of any good resources that can help with using data attributes, would appreciate you sharing. I can add the code that I tried using with the data attributes too if you’d like to see where I went wrong, just let me know. Thanks!

//function to append into the DOM:

function createList () {

        for (let i = 0; i < listArray.length; i++) {
          let newRow = document.createElement('tr');
          let newTitle = document.createElement('td');
          let newAuthor = document.createElement('td');
          let deleteButton = document.createElement('td');
          deleteButton.setAttribute('id','btn-wrapper');

          let deleteBtn = document.createElement('button');
          deleteBtn.setAttribute('class','remove-row');
          deleteBtn.setAttribute('data-index-number','[i]');
          deleteButton.appendChild(deleteBtn);

          newTitle.textContent = listArray[i].title;
          newAuthr.textContent = listArray[i].author;
          deleteBtn.textContent = 'Remove';

          newRow.appendChild(newTitle);
          newRow.appendChild(newAuthor);
          newRow.appendChild(deleteButton);
          tableInfo.appendChild(newRow);

          deleteBtn.addEventListener('click', function() {
              listArray.splice([i],1);
                tableInfo.innerHTML = '';
                createList();
           });
        }
    }

//function to add new books from form inputs:

bookSubmit.addEventListener(‘click’, function() {
tableInfo.innerHTML = ‘’;
const user1 = new User(bookTitle.value, bookAuthor.value);
listArray.push(user1);

        bookTitle.value = '';
        bookAuthor.value = '';

        createList();
    })