摘录一个Js实现getElementsByClassName()的程序:
function getElementsByClassName(className){ var elements = [];
if(!document.getElementsByClassName){ var domNodes = document.getElementsByTagName("*"); for(var i =0 ;i<domNodes.length;i++){ if(domNodes[i].className){ var classNames = domNodes[i].className.split(" "); /*这里其实还要考虑类名间隔大于一个空格的情况*/ for(var j = 0;j<classNames.length;j++){ if(classNames[j]==className){ elements.push(domNodes[i]); } } } } }else{
/*这里既然浏览器支持这个行为,为何不直接return document.getElementsByClassName(className) ???*/ var domNodes = document.getElementsByClassName(className); for(var i =0 ;i<domNodes.length;i++){ elements.push(domNodes[i]); } } return elements; }