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

135
Vistas
Checking if innerText of class is defined or not

I have a js script, which is extracting the innertext of a class. Sometimes that class is not rendered on the webpage, so for that case, innertext comes undefined. I want to keep a check for this so that this error is omitted. This is the code that I wrote ->

function myfunc() {          
    var button = document.getElementsByClassName('myclass');
    if (button[0].innerText !== undefined) {   
        console.log(button[0].innerText);
        clearInterval(x);
    } 
}

var x = setInterval(function() {
    myfunc();
}, 1)

So for the cases when the class is not there on the page, I was getting an undefined error hence I want to check that. I used an if condition in the code by checking if it is !== undefined but that is not working. Can anyone suggest some other methods? The error that I was getting ->

Uncaught TypeError: Cannot read property 'innerText' of undefined
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

This doesn't work, because document.getElementsByClassName('myclass') returns 0 buttons, so button[0] is already undefined.

You can solve this problem by using optional chaining:

if(button[0]?.innerText !== undefined){

The value on the left side is automatically undefined if something before the ? is undefined.

If button[0] doesn't exist / is undefined, JS won't even try to get the innerText property.

Or even easier

Just check the length:

if(button.length > 0) {
about 4 years ago · Juan Pablo Isaza Denunciar

0

You just need to check that button[0] exists before trying innerText on it. I cleaned it up a bit, but this should do the trick:

function checkForButton() {
   const button = document.querySelector('.myclass');
   if (button && button.textContent) {
     console.log(button.textContent);
     clearInterval(x);
   }
}
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