Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to getElementByClass instead of GetElementById with JavaScript?

I'm trying to toggle the visibility of certain DIV elements on a website depending on the class of each DIV. I'm using a basic JavaScript snippet to toggle them. The problem is that the script only uses getElementById, as getElementByClass is not supported in JavaScript. And unfortunately I do have to use class and not id to name the DIVs because the DIV names are dynamically generated by my XSLT stylesheet using certain category names.

I know that certain browsers now support getElementByClass, but since Internet Explorer doesn't I don't want to go that route.

I've found scripts using functions to get elements by class (such as #8 on this page: http://www.dustindiaz.com/top-ten-javascript/), but I can't figure out how to integrate them with with my toggle script.

Here's the HTML code. The DIVs themselves are missing since they are generated on page load with XML/XSLT.

Main Question: How do I get the below Toggle script to get Element by Class instead of get Element by ID?

<html>  <head>  <!--This is the TOGGLE script--> <script type="text/javascript"> <!--     function toggle_visibility(id) {        var e = document.getElementById(id);        if(e.style.display == 'block')           e.style.display = 'none';        else           e.style.display = 'block';     } //--> </script>  </head>  <!--the XML/XSLT page contents will be loaded here, with DIVs named by Class separating dozens of li's-->  <a href="#" onclick="toggle_visibility('class1');">Click here to toggle visibility of class 1 objects</a>  <a href="#" onclick="toggle_visibility('class2');">Click here to toggle visibility of class 2 objects</a>  </body> </html> 
like image 516
Alan Avatar asked Dec 19 '09 17:12

Alan


People also ask

What can I use instead of getElementById?

Yes, you can use the document. querySelectorAll function to query any CSS selector, or you can use document. getElementsByClassName to query based on class.

What is Getelementbyclass in JavaScript?

The getElementsByClassName method of Document interface returns an array-like object of all child elements which have all of the given class name(s). When called on the document object, the complete document is searched, including the root node.

What is difference between getElementById and getElementsByClassName?

getElementById returns a single DOM element whose ID matches your query. getElementsByClassName returns an HtmlCollection - an array-like structure containing the DOM elements that matched your query. You have to iterate through each element in the array to apply your style.

What is the difference between querySelector and getElementById?

With a querySelector statement, you can select an element based on a CSS selector. This means you can select elements by ID, class, or any other type of selector. Using the getElementById method, you can only select an element by its ID. Generally, you should opt for the selector that most clearly gets the job done.


2 Answers

The getElementsByClassName method is now natively supported by the most recent versions of Firefox, Safari, Chrome, IE and Opera, you could make a function to check if a native implementation is available, otherwise use the Dustin Diaz method:

function getElementsByClassName(node,classname) {   if (node.getElementsByClassName) { // use native implementation if available     return node.getElementsByClassName(classname);   } else {     return (function getElementsByClass(searchClass,node) {         if ( node == null )           node = document;         var classElements = [],             els = node.getElementsByTagName("*"),             elsLen = els.length,             pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)"), i, j;          for (i = 0, j = 0; i < elsLen; i++) {           if ( pattern.test(els[i].className) ) {               classElements[j] = els[i];               j++;           }         }         return classElements;     })(classname, node);   } } 

Usage:

function toggle_visibility(className) {    var elements = getElementsByClassName(document, className),        n = elements.length;    for (var i = 0; i < n; i++) {      var e = elements[i];       if(e.style.display == 'block') {        e.style.display = 'none';      } else {        e.style.display = 'block';      }   } } 
like image 170
Christian C. Salvadó Avatar answered Sep 21 '22 02:09

Christian C. Salvadó


Modern browsers have support for document.getElementsByClassName. You can see the full breakdown of which vendors provide this functionality at caniuse. If you're looking to extend support into older browsers, you may want to consider a selector engine like that found in jQuery or a polyfill.

Older Answer

You'll want to check into jQuery, which will allow the following:

$(".classname").hide(); // hides everything with class 'classname' 

Google offers a hosted jQuery source-file, so you can reference it and be up-and-running in moments. Include the following in your page:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <script type="text/javascript">   $(function(){     $(".classname").hide();   }); </script> 
like image 25
Sampson Avatar answered Sep 21 '22 02:09

Sampson