Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

190
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda