How to access elements having some Class using Javascript?

How to manipulate objects of all tags (suppose div) having some class name?

It can be achieved by first fetching all the div tags (or whichever you want) using function getElementsByTagName()

and then check their class name using another function className().

It gives us more flexibility apart from getElementsByID() and getElementsByName().

<script type="text/javascript">
var allDivs = new Array();

// pass parameter "classval" the classname you want to manipulate
function getElementsByClass(classval)
  //Populate the array with all the div tags in the document
  allDivs = document.getElementsByTagName('div');

  for (var i=0; i<allDivs.length; i++)
    var obj = allDivs[i];
    //if allDivs[i].className is null it will not go to second part of the if condition
    if ( (obj.className) && (obj.className == classval) )
      //do whatever you wish to this class
      if ( == "none")    //check if already hidden, if yes make it appear
  = "";
  = "none";    //if already appearing then hide here   
<a href="#" onclick="javascript:getElementsByClass('myclass') ; return false;">Click here</a>
<div class='myclass'>PHP</div>
<div class='myclass'>Javascript</div>
<div class='myclass'>Perl</div>
<div class='myclass'>AJAX</div>
<div class='myclass'>HTML</div>
<div class='myclass'>MySQL</div>

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>