Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

189
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda