deligation.addEventListener is not a function – Why

Issue

    const deligation = document.querySelectorAll(".contents_box");

    function deligationFunc(e){
        let elem = e.target; 
        console.log(elem);

        while(!elem.getAttribute('data-name')){
            elem = elem.parentNode;
            if(elem.nodeName === 'BODY'){ 
                elem = null;
                return;
            } 
        }

        elem.classList.toggle('on'); 
    }

    if(deligation){
        deligation.addEventListener('click', deligationFunc);
    }

deligation has multiple node lists from DOM
SO I tried

for(let i=0; i<deligation.length; i++){
        deligation.addEventListener('click', deligationFunc);
    }

Instead of
deligation.addEventListener('click', deligationFunc);

However, it wasnt working again.

On the other hand
window.addEventListener('click', deligationFunc);
is working well.

I have no idea with deligation.

Solution

Your initial way of thinking with the loop is correct, but how you handle it is wrong. Since you are using a for loop, you have to specify the index of the element that you are attaching your listener to. A more simple approach would be the forEach() loop instead.

Using forEach() :

function deligationFunc(e){
    let elem = e.target; 
    console.log(elem);

    while(!elem.getAttribute('data-name')){
        elem = elem.parentNode;
        if(elem.nodeName === 'BODY'){ 
            elem = null;
            return;
        } 
    }

    elem.classList.toggle('on'); 
}

const deligation = document.querySelectorAll(".contents_box");

deligation.forEach(item => {
  item.addEventListener('click', e => { deligationFunc(e) });
});

Using for() :

function deligationFunc(e){
    let elem = e.target; 
    console.log(elem);

    while(!elem.getAttribute('data-name')){
        elem = elem.parentNode;
        if(elem.nodeName === 'BODY'){ 
            elem = null;
            return;
        } 
    }

    elem.classList.toggle('on'); 
}

const deligation = document.querySelectorAll(".contents_box");

for (let i = 0; deligation.length > i; i++) {
    deligation[i].addEventListener('click', e => { deligationFunc(e) });
}

Answered By – Martin

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published