Skip to content

Instantly share code, notes, and snippets.

@andy12530
Created November 13, 2012 08:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andy12530/4064621 to your computer and use it in GitHub Desktop.
Save andy12530/4064621 to your computer and use it in GitHub Desktop.
为不支持的浏览器添加getElementsByClassName与querySelectorAll方法
/*
document.getElementById();
document.getElementsByTagName();
document.getElementsByName();
以上三种方法在主流浏览器中得到原生支持,但是通过class取得元素以及通过css选择器的方式取得元素,即
getElementsByClassName与querySelectorAll未在IE6、7、8中得到完全支持
*/
function each(elem, callback) {
if (elem.length !== undefined) {
for(var i=0, len = elem.length; i<len; i++) {
if (callback.call(elem[i], i, elem[i]) === false)
break;
}
} else {
for(name in elem) {
callback.call(elem[name], name, elem[name]);
}
}
}
function getClass(className, elem) {
var elem = elem || document;
if (document.getElementsByClassName) {
return elem.getElementsByClassName(className);
} else {
var rs = [];
each(elem.getElementsByTagName("*"), function(i) {
if (/\b+ className +\b/.test(this.className)) {
rs.push(this);
}
})
return rs;
}
}
/*
动态添加一张样式表(document.createStyleSheet(),chrome不支持),用选择器添加一条规则,然后拿出符合规则的元素,
清空样式表。
原因:querySelectorAll仅在ie6/7上不支持。
*/
function getQuerySelectorAll(selector) {
if (document.querySelectorAll) {
return documnet.querySelectorAll(selector);
} else {
var styleSheet = document.createStyleSheet(), rs = [];
styleSheet.addRule(selector, "a:b");
each(document.getElementsByTagName("*"), function(i) {
if (this.currentStyle.a === 'b') {
rs.push(this);
}
})
styleSheet.cssText = '';
return rs;
}
}
@andy12530
Copy link
Author

参考qatrix.js中的一些方法。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment