Quick way to getElementsByClass in HTML DOM

In this example I'll find all the elements with the class name "hideMe" and then hide/show them.

<script type="text/javascript">
<!--
  function getElementsByClass(node,searchClass,tag) {
    var classElements = new Array();
        if ( node == null )
            node = document;
        if ( tag == null )
            tag = '*';
    var els = node.getElementsByTagName(tag); // use "*" for all elements
    var elsLen = els.length;
    var pattern = new RegExp("\\b"+searchClass+"\\b");
    for (i = 0, j = 0; i < elsLen; i++) {
         if ( pattern.test(els[i].className) ) {
         classElements[j] = els[i];
         j++;
         }
    }
    return classElements;
  }

  function hideByClass(theClass) {
    var el = getElementsByClass(document,theClass);
    var elLength = el.length;
    for (i = 0; i < elLength; i++ ){
        el[i].style.display = "none";
    };
  }
  function showByClass(theClass) {
    var el = getElementsByClass(document,theClass);
    var elLength = el.length;
    for (i = 0; i < elLength; i++ ){
        el[i].style.display = "block";
    };
  }
  //-->
</script>

<body>
  <a href="javascript:void(0);" onClick="hideByClass('hideMe');" >Hide class<em>ified</em> elements</a> | <a href="javascript:void(0);" onClick="showByClass('hideMe');" >Show class<em>ified</em> elements</a>
  <div id="unique123" class="hideMe">Some random text</div>
  <div id="some123" class="hideMe">Some random text again</div>
  <div id="random" class="hideMe">Some random text again and again</div>
  <input id="123" class="hideMe" name="aValue" value="Even and Input"></input><button class="hideMe">and a button too</button>
</body>

Try It! Hide classified elements | Show classified elements
Some random text
Some random text again
Some random text again and again

0 Responses to “Quick way to getElementsByClass in HTML DOM”


  1. No Comments

Leave a Reply