I tried to do it like this:
const cards=document.querySelectorAll(".card")
for(const card of cards){
card.addEventListener('click',()=>{
console.log("Hello")
})
}
Here I have created the div, which has a class name card.
const createCard=(data)=>{
const div=document.createElement("div")
div.classList.add("card")
div.innerHTML=`
<h1>${data.name}</h1>
<img src=${data.sprites.other.dream_world.front_default} alt=${data.name}></img>
<p>${data.base_experience}</p>
`
return div
}
I want that when we click any card then Hello will be printed in the console, but it is not working and it is not showing any error. I tried using document.getElementsbyClassName
too, but still no output is shown. What is the problem with this. We can’t apply Event listener to a div?
I tried with a button and the same code is working. Then why it is not working with div?
2
Answers
This code of yours …
only add
.addEventListener
to.card
that currently have in HTML not include.card
you will create later withcreateCard(data)
So you need to add
.addEventListener
to evey.card
you create.there might be an issue with "event delegation" if you are creating these divs dynamically (e.g., after the page has initially loaded). In that case, you should apply the event listener to the document or a static parent element that contains these divs and then check which element with the "card" class was actually clicked. Here’s how you can do it:
This way, the event listener is applied to the document but checks if the clicked element has the "card" class before performing the desired action. This should work correctly even for dynamically created divs. I hope it helps you