为了得到需要的元素列表,我们会组合使用DOM API来得到,这种繁密的过程效率低下。
新版本浏览器提供了querySelectorAll css选择器将会快2至6倍
document.querySelectorAll('#menu a');
API document.getElementById('menu').getElementsByTagName('a');
两者区别 css选择器获得是nodeList 包含着匹配节点的类数组对象,非html集合,不会对应实时的文档对象,为静态列表
后者为html集合,会有性能问题 toArray
function toArray(coll) {
for(var i=0,a=[],len = coll.length; i< coll; i++) {
a.push(coll[i]);
}
return a;
}
querySelectorAll更适合组合查询
document.querySelectorAll('div.warning,div.notice');
var errs = [],
divs = document.getElementsByTagName('div'),
div = null;
className = '';
for(var i = 0, len = divs.length;i < len; i++) {
div = divs[i];
className = div.className;
if(className === 'notice' || className === 'warning') {
errs.push(div);
}
}
选择第一个匹配的节点
document.querySelector() 返回 第一个引用
IE8支持这样的API