How can I check if the querySelector of a clicked element is correct using if statement?

1.3k Views Asked by At

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?

1

There are 1 best solutions below

0
On

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 the window object and then catch all propagated click events. Instead of that, try to find your whatsApp button via document.querySelector and addEventListener directly to it. Something like:

const whatsApp = document.querySelector('a[href*="whatsapp.com"]')
whatsApp.addEventListener('click', ev => {
  console.log('Hey WhatsApp!')
})

querySelector documentation