getElementsByClassName IE resolution issue

Ryan Sharp picture Ryan Sharp · Dec 10, 2010 · Viewed 11.7k times · Source

I am having issues figuring out how to resolve the getElementsByClassName issue in IE. How would I best implement the robert nyman (can't post the link to it since my rep is only 1) resolution into my code? Or would a jquery resolution be better? my code is

function showDesc(name) {
var e = document.getElementById(name);
//Get a list of elements that have a class name of service selected
var list = document.getElementsByClassName("description show");

//Loop through those items
for (var i = 0; i < list.length; ++i) { 
    //Reset all class names to description
    list[i].className = "description";
}

if (e.className == "description"){
    //Set the css class for the clicked element
    e.className += " show";
}
else{
    if (e.className == "description show"){
        return;
    }
}}

and I am using it on this page dev.msmnet.com/services/practice-management to show/hide the description for each service (works in Chrome and FF). Any tips would be greatly appreciated.

Answer

alex picture alex · Dec 10, 2010

This should support multiple classes.

function getElementsByClassName(findClass, parent) {

  parent = parent || document;
  var elements = parent.getElementsByTagName('*');
  var matching = [];

  for(var i = 0, elementsLength = elements.length; i < elementsLength; i++){

    if ((' ' + elements[i].className + ' ').indexOf(findClass) > -1) {
      matching.push(elements[i]);
    }

  }

  return matching;

}

You can pass in a parent too, to make its searching the DOM a bit faster.

If you want getElementsByClassName('a c') to match HTML <div class="a b c" /> then try changing it like so...

var elementClasses = elements[i].className.split(/\s+/),
    matchClasses = findClass.split(/\s+/), // Do this out of the loop :)
    found = 0;

for (var j = 0, elementClassesLength = elementClasses.length; j < elementClassesLength; j++) {

    if (matchClasses.indexOf(elementClasses[j]) > -1) {
        found++;
    }

}

if (found == matchClasses.length) {
   // Push onto matching array
}

If you want this function to only be available if it doesn't already exist, wrap its definition with

if (typeof document.getElementsByClassName != 'function') { }