Problem
getElementsByClassName not working in IE
Introduction
getElementByClassName works in almost all browsers like Chrome, Mozilla but not with IE. This is one of the journal problem faced by JavaScript developers. I have also suffered with this problem when I was a beginner to JavaScript.
Erroneous Code
In following code we are hiding all images with class name "class_image". following code will work fine in All browsers except IE
function hide_all_images(){ ele=document.getElementsByClassName('class_image'); for(i=0; i<ele.length; i++){ ele[i].style.display="none"; } }
Solutions
In following code we are using document.getElementByTagName('*') to get all the element of HTML document. In next step will will traverse the array "ele" and check if the class name of the element is equals to 'class_name' using ele[i].className and if it is equals to 'class_name' we will set "desplay" property of element to "none"
function hide_all_images(){ ele=document.getElementsByTagName('*'); for(i=0; i<ele.length; i++){ if(ele[i].className=='class_image'){ ele[i].style.display="none"; } } }