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

Viewed 6004

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.

3 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');
    }))
});

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');
        });
    });
});

document.querySelectorAll() is returns a NodeList so you can't add an eventListener. You can try to visit all elements with for loop and add eventListener for each one.

window.addEventListener('DOMContentLoaded', (event) => {
     var x = document.querySelectorAll("a[href='example.com']");
     for(i=0;i<x.length; i++){
         x[i].addEventListener('click',function (e) {
                newrelic.addPageAction('Doc');
    
            })
        });
Related