I have a "Create Card" button and made it such that anytime it is clicked, two things happen. An item is added to an array and a card containing a delete button is created. Each button has a data attribute that is gotten from the index of the corresponding item in the array. When a delete button on a card is clicked, the card is removed and the corresponding item that has an index equal to the data attribute of the clicked button is also removed from the array. However, when this happens, the indexes of the items in the array updates themselves but the values given to the data attributes of the buttons when they were created do not update alongside the indexes of their corresponding item in the array. This results in the items in the array not getting removed according to the delete button being clicked. How do I fix this? The code is below. (Sorry for the long write up)
// DOM Element Selectors
const cardContainer = document.querySelector('#card-container');
const createCardBtn = document.querySelector('#create-card-btn');
// Event Listeners
createCardBtn.addEventListener('click', addCardtoArray);
cardArray = [];
function addCardtoArray() {
let cardIndex = cardArray.length;
cardArray.push(cardIndex);
console.log(cardArray);
displayCard();
}
function displayCard() {
cardContainer.innerHTML = '';
cardArray.forEach(card => {
cardIndex = cardArray.indexOf(card);
let btnContainer = document.createElement('div');
btnContainer.className = 'btn-container';
btnContainer.innerHTML = `<button class="delete-btn" data-btnindex="${cardIndex}">Delete</button>`;
cardContainer.appendChild(btnContainer);
});
const deleteBtns = document.querySelectorAll('.delete-btn');
[...deleteBtns].forEach(deleteBtn => {
deleteBtn.addEventListener('click', () => {
let dbIndex = deleteBtn.dataset.btnindex;
cardArray.splice(dbIndex, 1);
const btnContainer = deleteBtn.parentElement;
const cardContainer = btnContainer.parentElement;
cardContainer.removeChild(btnContainer);
console.log(cardArray);
});
});
}
body {
display: flex;
flex-direction: column;
justify-content: center;
gap: 6rem;
padding: 5rem 0;
}
#create-card-btn-container {
display: flex;
justify-content: center;
}
#card-container {
display: grid;
grid-template-columns: repeat(4, 1fr);
justify-content: center;
align-items: center;
row-gap: 4rem;
}
.btn-container {
background: #c4c4c4;
text-align: center;
border: 3px solid #666666;
padding: 4rem 6rem;
margin: 0rem 2rem;
}
<body>
<div id="create-card-btn-container">
<button id="create-card-btn">Create Card</button>
</div>
<div id="card-container">
</div>
<script src="script.js"></script>
</body>