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

184
Visualizações
Progress all the same Class found inside the DOM

I want to turn off the display of all DIVs labeled readerPanelsRight in the class of the DIV element, but I am getting this error.

The page contains readerPanelsRight but I still get the "undefined" error. What is the problem?

function updateStyleWithClass(elmId, value) {
   var elem = document.getElementsByClassName(elmId);
   if (typeof elem !== 'undefined' && elem !== null) {
       elem[0].style.display = value;
     }
 }

function tabShowing(tabID) {
    var classMatcher = /(?:^|\s)readerPanelsRight(?:\s|$)/;
    var els = document.getElementsByTagName('*');
    for (var i = els.length; i--;) {
        if (classMatcher.test(els[i].className)) {
            updateStyleWithClass(els[i], 'none');
        }
    }
    // Element ID is showing code here..
}

HTML:

<a href="#" onclick="tabShowing('elementID_1')">button_1</a>
<a href="#" onclick="tabShowing('elementID_2')">button_2</a>
<a href="#" onclick="tabShowing('elementID_3')">button_3</a>

<div class="readerPanelsRight" id="elementID_1"></div>
<div class="readerPanelsRight" id="elementID_2"></div>
<div class="readerPanelsRight" id="elementID_3"></div>

Console:

Uncaught TypeError: elem[0] is undefined

Thank you.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You're making this much more complicated than it needs to be. Use getElementsByClassName() to get the elements to loop over, not getElementsByTagId(). And in updateStyleWithClass(), the argument is the element, you don't need to call another get function.

function updateStyleWithClass(elem, value) {
  elem.style.display = value;
}

function tabShowing(tabID) {
  var els = document.getElementsByClassName('readerPanelsRight');
  for (var i = els.length; i--;) {
    updateStyleWithClass(els[i], 'none');
  }
  let selected_tab = document.getElementById(tabID);
  if (selected_tab) {
    updateStyleWithClass(selected_tab, "block");
  }
}

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