Facebook
Banner
XMPP JavaScript Library READ MORE

Solution for "getElementsByClassName not working in IE"

JavaScript, Sachin Puri, 2012-01-24 22:24:30

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"; 
        }
    }
}

 

Add Your Comment
   
    Yes! I want to receive all comments by email

No Comments Posted Yet. Be the first one to post comment