Home  >  Article  >  Web Front-end  >  Solution to the problem that IE browser does not support getElementsByClassName_javascript skills

Solution to the problem that IE browser does not support getElementsByClassName_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:38:241210browse

The getElementsByClassName method has been added to DOM3, but it is not supported by other versions except IE9 and 10. This is a pain!
The current solution is to determine whether the browser supports this method. If it supports it, leave it alone. If it does not support it, add the getElementsByClassName method to the document object. This way of writing has the advantage that you don’t have to go there regardless of whether there is a native function or not. Modify the code.

Some people on the Internet directly define a getElementsByClassName function, but in this case, all uses of document.getElementsByClassName in the code need to be rewritten into getElementsByClassName. It's somewhat inconvenient and not universal.

The following method perfectly supports document writing:

if(!document.getElementsByClassName){
  document.getElementsByClassName = function(className, element){
    var children = (element || document).getElementsByTagName('*');
    var elements = new Array();
    for (var i=0; i<children.length; i++){
      var child = children[i];
      var classNames = child.className.split(' ');
      for (var j=0; j<classNames.length; j++){
        if (classNames[j] == className){ 
          elements.push(child);
          break;
        }
      }
    } 
    return elements;
  };
}
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn