Home >Web Front-end >JS Tutorial >How do you retrieve elements by class in JavaScript when getElementByClass is not supported?
Getting Elements by Class in JavaScript
In JavaScript, the getElementById method is commonly used to retrieve elements by their unique identifiers. However, some scenarios require retrieving elements based on their class names, and since JavaScript doesn't natively support getElementByClass, an alternative approach is necessary.
Dustin Diaz Method:
One method to retrieve elements by class is the function created by Dustin Diaz:
<code class="javascript">function getElementByClass(searchClass, node) { if (node == null) { node = document; } var classElements = []; var els = node.getElementsByTagName("*"); var elsLen = els.length; var pattern = new RegExp("(^|\s)" + searchClass + "(\s|$)", "i"); var i; var j = 0; for (i = 0; i < elsLen; i++) { if (pattern.test(els[i].className)) { classElements[j] = els[i]; j++; } } return classElements; }</code>
Usage:
This function can be used in conjunction with the toggle script provided in the question:
<code class="javascript">function toggle_visibility(className) { var elements = getElementByClass(className, document); var 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>
Native Method:
In recent versions of major browsers like Firefox, Chrome, IE, and Opera, the getElementsByClassName method is supported natively. This simplifies the process of retrieving elements by class:
<code class="javascript">function getElementsByClassName(className, node) { if (node.getElementsByClassName) { return node.getElementsByClassName(className); } else { // Use Dustin Diaz method as fallback return getElementByClass(className, node); } }</code>
The above is the detailed content of How do you retrieve elements by class in JavaScript when getElementByClass is not supported?. For more information, please follow other related articles on the PHP Chinese website!