Home > Article > Web Front-end > Why Choose `getElementsByClassName` over `getElementById` in JavaScript?
Get Elements by Class: An Alternative to getElementById in JavaScript
In the realm of web development, the getElementById method reigns supreme when it comes to accessing specific elements within an HTML document. However, there are instances where leveraging getElementByClass can prove more suitable.
With the emergence of modern browsers like Firefox and Chrome, getElementByClass has emerged as a natively supported feature. However, for browsers like Internet Explorer, a workaround is necessary to emulate its functionality.
Creating a Custom getElementsByClass Function
Dustin Diaz, a renowned JavaScript expert, has devised an ingenious solution to address the lack of native getElementByClass support. His approach involves creating a custom function that mimics its behavior:
<code class="javascript">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); } }</code>
Integrating the Function with the Toggle Script
To seamlessly integrate this custom function with the provided toggle script, simply replace the getElementById calls with getElementsByClassName, as seen below:
<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'; } } }</code>
Conclusion
By implementing this custom getElementsByClass function, you can leverage the class attribute to toggle the visibility of elements, even when native support for getElementByClass is lacking. This solution empowers developers to harness the benefits of class-based element identification, ensuring consistent behavior across different browsers.
The above is the detailed content of Why Choose `getElementsByClassName` over `getElementById` in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!