本身動手實現getElementsByClassName

看了一句話,咱們都是搬運工,github的搬運工,下面這代碼搬運來自各個地方,最後成型。git

var classCache = {};
function getElementsByClassName(cls, root, tag){
var elems, classRE,
rs = [];
root = root || document;
tag = tag || '*';
elems = root.getElementsByTagName(tag);
//去掉字符串先後空格
cls = cls.replace(/^\s+|\s+$/g, '').split(/\s+/g);
cls = cls.join('\\s+[\\S]*\\s*');

classRE = classCache[cls] || new RegExp('(^|\\s+)' + cls + '(\\s+|$)');
for(var i = 0, len = elems.length; i < len; i++){
classRE.test(elems[i].className) && rs.push(elems[i]);
}
return rs;
}github

相關文章
相關標籤/搜索