first post here.
I was trying to make some tests using the if statement to fire an Alert
, for example, when there's a lot of whatsApp buttons on website, but with difference in specifications on it.
So i tried to run this code:
window.addEventListener('click', function(event){
if(event.target.querySelector('a[href*="whatsapp.com"]')){
console.log('Hey WhatsApp!')
}
})
But this code isn't works, it does not return an error on Console, but it does not fires the console.log
You guys knows what is wrong with this code or if there's a way to validate on the if
statement the querySelector
of a clicked button?
I think, you misunderstanding what
querySelector
is used for. This method returns first child element, whose selector is matched with that you passed as an argument.Maybe, you don't want to
addEventListener
to thewindow
object and then catch all propagated click events. Instead of that, try to find your whatsApp button viadocument.querySelector
andaddEventListener
directly to it. Something like:querySelector documentation