Home > Software engineering >  deligation.addEventListener is not a function - Why
deligation.addEventListener is not a function - Why

Time:10-04

    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.

CodePudding user response:

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

CodePudding user response:

querySelectorAll() returns a NodeList (it's like an Array), so you need to access it's items by index. Change your code to:

if (deligation.length) {
    deligation[0].addEventListener('click', deligationFunc);
}

Or, better, and works if you have more than one matching element:

for (const element of deligation) {
    element.addEventListener('click', deligationFunc);
}
  • Related