最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Getting error Uncaught TypeError: document.querySelectorAll(...).addEventListener is not a function - Stack Overflo

programmeradmin4浏览0评论

I've got the script below

window.addEventListener('DOMContentLoaded', (event) => {
document.querySelectorAll("a[href='example']").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.

I've got the script below

window.addEventListener('DOMContentLoaded', (event) => {
document.querySelectorAll("a[href='example.']").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.

Share Improve this question asked Aug 28, 2020 at 12:01 SalmanSalman 1,8716 gold badges15 silver badges28 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 7

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.']")].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.']").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.']");
     for(i=0;i<x.length; i++){
         x[i].addEventListener('click',function (e) {
                newrelic.addPageAction('Doc');
    
            })
        });

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论