I am trying to switch the visibility of certain DIV elements on a website depending on the class of each DIV. I use the basic Javascript snippet to switch them. The problem is that the script uses only getElementById, since getElementByClass is not supported in Javascript. And, unfortunately, I have to use a class, not id, to call a DIV, because DIV names are dynamically generated by my XSLT stylesheet using specific category names.
I know that some browsers now support getElementByClass, but since Internet Explorer I donβt want to go that route.
I found scripts using functions to get elements by classes (for example, # 8 on this page: http://www.dustindiaz.com/top-ten-javascript/ ), but I cannot figure out how to integrate them using my switch script.
Here is the html code. DIVs themselves are missing, as they are generated when the page loads using XML / XSLT. Thank you very much in advance.
Main question: How to get below a Toggle script to get an Element by Class instead of an Element by ID?
<html> <head> <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> <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>
javascript class toggle getelementbyid getelementsbyclassname
Alan Dec 19 '09 at 17:38 2009-12-19 17:38
source share