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

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

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 Relatório

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 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