Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting error Uncaught TypeError: document.querySelectorAll(...).addEventListener is not a function

I've got the script below

window.addEventListener('DOMContentLoaded', (event) => {
document.querySelectorAll("a[href='example.com']").addEventListener('click',function (e) {
            newrelic.addPageAction('Doc');

        })
    });

I am trying to capture count of hits whenever the user opens the document enclosed within anchor tag with href present but no ID property. The document opens in another window. Is the above correct way to use.

like image 574
Salman Avatar asked Sep 08 '25 11:09

Salman


2 Answers

Because querySelectorAll returns a collection of elements, so you should iterate over it ad add the event listener

window.addEventListener('DOMContentLoaded', (event) => {
    [...document.querySelectorAll("a[href^='example.com']")].forEach(el => el.addEventListener('click',function (e) {
            newrelic.addPageAction('Doc');
    }))
});
like image 53
Alberto Sinigaglia Avatar answered Sep 10 '25 01:09

Alberto Sinigaglia


You need to go through each element returned by querySelectorAll()

window.addEventListener('DOMContentLoaded', (event) => {
    document.querySelectorAll("a[href='example.com']").forEach(el => {
        el.addEventListener('click',function (e) {
            newrelic.addPageAction('Doc');
        });
    });
});
like image 39
Dan Mullin Avatar answered Sep 10 '25 00:09

Dan Mullin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!