Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

javascript - document.getElementByClassName - Cross Browser Fix

I have looked at previous asks for help in a cross browser fix for document.getElementByClassName and found this link which provided a seemingly perfect fix.

However I have tried implementing it on a site that I have built but can not get the fix to work (or any others) on IE8 (the browser which I am working to get compatability with). I am still getting the "Object or Property is not supported" error meaning that the fix is obviously not working.

Coming up short for any reasons why this may not be working correctly and unable to find anyone with problems getting it to work I ask if you would be able to help me in getting this fix working.

The site I am trying to the fix working on is http://lifeswitch.org.nz.s125738.gridserver.com/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This works (tested):

function getElementsByClassName(cn, rootNode) {
  if (!rootNode) {
    rootNode = document;
  } 
  for (var r=[], e=rootNode.getElementsByTagName('*'), i=e.length; i--;) {
    if ((' '+e[i].className+' ').indexOf(' '+cn+' ')>-1) {
      r.push(e[i]); 
    }
  }
  return r;  
}

You could probably get away with adding it to Node.prototype, like this:

Node.prototype.getElementsByClassName = function(cn) {
  for (var r=[], e=this.getElementsByTagName('*'), i=e.length; i--;) {
    if ((' '+e[i].className+' ').indexOf(' '+cn+' ')>-1) {
      r.push(e[i]); 
    }
  }
  return r;  
}

That should add it to browsers that don't have it, but it should be shadowed by browsers that do have it since they provide it farther down the prototype chain (not tested).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...