Home >Web Front-end >JS Tutorial >How to Select HTML Elements by Class Name in JavaScript?
How to getElementByClass with JavaScript?
Question:
You aim to toggle the visibility of DIV elements based on their class using a JavaScript snippet. However, the current script relies on getElementById, which is not suitable because the DIV names are dynamically generated using XSLT.
Answer:
getElementsByClassName Method:
Modern browsers natively support the getElementsByClassName method. You can check for its availability and use it if supported.
Dustin Diaz Method (For Older Browsers):
For older browsers, employ the Dustin Diaz method:
<code class="javascript">function getElementsByClassName(node, classname) { if (node.getElementsByClassName) { // Native implementation exists 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); } }
Updated Toggle Script:
Utilize the getElementsByClassName method or Dustin Diaz fallback in your toggle script:
<code class="javascript">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'; } } }
Usage:
In your HTML, modify the onclick attributes of your toggle links to reference the new toggle_visibility function:
<code class="html"><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></code>
The above is the detailed content of How to Select HTML Elements by Class Name in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!