I'm trying to create something like this,
when I click on submit
each task card add to the Tasks but when I'm trying to delete a card for example task2 by clicking x
red button
it first deletes task1 and then task2
here is my code I gave the close button an onclick()
button:
'use strict'
const submitBtn = document.querySelector('#submit')
const inputVal = document.querySelector('.title')
const dateVal = document.querySelector('.date')
let taskDiv = document.querySelector('#task')
submitBtn.addEventListener("click" , function(event){
event.preventDefault()
let card = document.createElement('div')
card.classList.add('card')
card.innerHTML=`
<div >
<h3>${inputVal.value}</h3>
<button id="closeTasks" onclick="closeTask()">x</button>
</div>
<span>start : ${dateVal.value}</span>
<span>end : </span>
<div >
<button id="minimize"><i ></i></button>
<button id="info"><i ></i></button>
<button id="next"><i ></i></button>
</div>
`
taskDiv.appendChild(card)
})
function closeTask(){
let card = document.querySelector(".card")
card.remove()
}
CodePudding user response:
the issue come from document.querySelector(".card")
it will return the first element that match the selector (here .card) but not necessary the one you need
an idea can be to pass the event as parameter of your function and use target to access clicked button.
To remove all the card you can use element.closest
to get the closest element match card class
function closeTask(event) {
const card = (event.target || event.srcElement).closest(".card");
card.remove()
}
function closeTask(event) {
const card = (event.target || event.srcElement).closest(".card");
card.remove();
}
<div >
<button onclick="closeTask(event)">X</button> card 1
</div>
<div >
<button onclick="closeTask(event)">X</button> card2
</div>