从您的评论来看,听起来您只是想决定是否可以使用document.getElementsByClassName()
. 如果是这种情况,您可以像这样使用特征检测:
if (document.getElementsByClassName) {
// code here that uses getElementsByClassName
} else {
// code here that doesn't use getElementsByClassName
}
只安装一个 polyfill 可能会更干净,这样您就可以在旧版本的 IE 中使用它,而无需先检查。您可以通过 Google 搜索找到其中的一些。这是一个:
// Add a getElementsByClassName function if the browser doesn't have one
// Limitation: only works with one class name
// Copyright: Eike Send http://eike.se/nd
// License: MIT License
if (!document.getElementsByClassName) {
document.getElementsByClassName = function(search) {
var d = document, elements, pattern, i, results = [];
if (d.querySelectorAll) { // IE8
return d.querySelectorAll("." + search);
}
if (d.evaluate) { // IE6, IE7
pattern = ".//*[contains(concat(' ', @class, ' '), ' " + search + " ')]";
elements = d.evaluate(pattern, d, null, 0, null);
while ((i = elements.iterateNext())) {
results.push(i);
}
} else {
elements = d.getElementsByTagName("*");
pattern = new RegExp("(^|\\s)" + search + "(\\s|$)");
for (i = 0; i < elements.length; i++) {
if ( pattern.test(elements[i].className) ) {
results.push(elements[i]);
}
}
}
return results;
}
}