Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k 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 Reply

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...