javascriptgetelementsbytagname

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.


Solution

  • 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");
      }
    }