Skip to content Skip to sidebar Skip to footer

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) {

Solution 1:

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

Solution 2:

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

Solution 3:

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

Post a Comment for "Getting Error Uncaught TypeError: Document.querySelectorAll(...).addEventListener Is Not A Function"