Home > Back-end >  element.classList.contains() eaquals to undefined. Why?
element.classList.contains() eaquals to undefined. Why?

Time:11-06

Code below displays undefined:

function search(){
    let clas = document.querySelector('input#search').value;
    if(clas=="Speed"){
        clas="v";
    }else if(clas=="Dro"){
        clas="s";
    }else if(clas=="Cza"){
        clas="t";
    }else if(clas=="Przys"){
        clas="a";
    }
    find(clas);
}
function find(clas="*"){
        const elements = document.querySelector("main").childNodes;
        if(clas!="*"){
            console.log(elements[0].classList.contains("v"));
        }
}

I wanted to check if elements of main contain class "v" but my every attempt concludes with an error:

script.js:17 Uncaught TypeError: Cannot read properties of undefined (reading 'contains') at find (script.js:17) at search (script.js:12) at HTMLButtonElement.onclick (calculator.html:18) find @ script.js:17 search @ script.js:12 onclick @ calculator.html:18

Main contains elements! I do not understand what I've done wrong and how to fix it. Could someone explain and help?

CodePudding user response:

The error tells you that you're trying to use contains on the value undefined. That tells us that the first child node of the main element is not an element (perhaps it's a text or comment node; often it's a text node with whitespace). Only element nodes have classList. So elements[0].classList is undefined.

You may have wanted children rather than childNodes, if you wanted only element children.

Here's an example of the difference:

Show code snippet

const main = document.querySelector("main");
console.log("childNodes[0].nodeName:", main.childNodes[0].nodeName);
console.log("children[0].nodeName:", main.children[0].nodeName);
<main>
    <p>Hi there</p>
</main>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Or if you're only going to use the first one, you could use firstElementChild instead of children[0].

  • Related