Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

187
Views
element.classList.contains() eaquals to undefined. Why?

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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:

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>

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!