Retrieving Elements by Class in JavaScript, Including IE Compatibility
Getting an array of elements based on their class is a common task in JavaScript. However, for browsers that do not natively support document.getElementsByClassName(), such as IE, an alternative approach is needed.
One popular solution is the function by Jonathan Snook. This function employs a regular expression to test the className property of each element. However, in IE, it throws an error stating "Object doesn't support this property or method."
The key is to realize that getElementsByClassName() is not a method of the document object. Instead, it should be called directly on the node where you want to search for elements:
function getElementsByClassName(node, classname) { var a = []; var re = new RegExp('(^| )' + classname + '( |$)'); var els = node.getElementsByTagName("*"); for (var i = 0, j = els.length; i < j; i++) { if (re.test(els[i].className)) a.push(els[i]); } return a; } var tabs = getElementsByClassName(document.body, 'tab');
For IE8 , a more concise approach is to polyfill the getElementsByClassName() function:
if (!document.getElementsByClassName) { document.getElementsByClassName = function (className) { return this.querySelectorAll("." + className); }; Element.prototype.getElementsByClassName = document.getElementsByClassName; } var tabs = document.getElementsByClassName('tab');
With these techniques, you can retrieve elements by class, ensuring compatibility with IE and other browsers.
The above is the detailed content of How Can I Retrieve Elements by Class in JavaScript, Especially for IE Compatibility?. For more information, please follow other related articles on the PHP Chinese website!