不能获取class为多个的情况
function getByClass(parent,cls){ var res=[]; var ele=parent.getElementsByTagName("*"); for(var i=0;i<ele.length;i++){ if(ele[i].className==cls){ res.push(ele[i]); } } return res; }
把除字母、数字、下划线的其它字符都当成是边界,当class为像abc-test时可能获取不准确
function getByClass(parent,cls){ var res=[]; var reg=new RegExp("\b"+cls+"\b",i); var ele=parent.getElementsByTagName("*"); for(var i=0;i<ele.length;i++){ if(reg.test(ele[i].className)){ res.push(ele[i]); } } return res; }
有空格
function getByClass(parent,cls){ var res=[]; var reg=new RegExp(" "+cls+" ",i); var ele=parent.getElementsByTagName("*"); for(var i=0;i<ele.length;i++){ if(reg.test(" "+ele[i].className+" ")){ res.push(ele[i]); } } return res; }
空格使用正则来处理
function getByClass(parent,cls){ var res=[]; var reg=new RegExp('(^|\s)'+cls+'($|\s)','i'); var ele=parent.getElementsByTagName("*"); for(var i=0;i<ele.length;i++){ if(reg.test(ele[i].className)){ res.push(ele[i]); } } return res; }
结合getElementsByClassName()
function getByClass(parent,cls){ if(parent.getElementsByClassName){ return parent.getElementsByClassName(cls); } else{ var res=[]; var reg=new RegExp(" "+cls+" ","i"); var ele=parent.getElementsByTagName("*"); for(var i=0;i<ele.length;i++){ if(reg.test(" "+ele[i].className+" ")){ res.push(ele[i]); } } return res; } }