下面是个小演示: 我是 id 为 test 的 div 感觉区别不大是吧,但如果是稍微复杂点的情况,原始的方法将变得非常麻烦,这时候 querySelector 和 querySelectorAll 的优势就发挥出来了。比如接下来这个例子,我们将在 document 中选取 class 为 test 的 div 的子元素 p 的第一个子元素,当然这很拗口,但是用本文的新方法来选择这个元素,比用言语来描述它还要简单。
var emphasisText = document.querySelectorAll(".emphasis");for( var i = 0 , j = emphasisText.length ; i < j ; i++ ){emphasisText[i].style.fontWeight = "bold";}
这是原生方法,比起jquery速度快,缺点是IE6、7不支持。
W3C的规范与库中的实现
querySelector:return the first matching Element node within the node"s subtrees. If there is no such node, the method must return null .(返回指定元素节点的子树中匹配selector的集合中的第一个,如果没有匹配,返回null) querySelectorAll:return a NodeList containing all of the matching Element nodes within the node"s subtrees, in document order. If there are no such nodes, the method must return an empty NodeList. (返回指定元素节点的子树中匹配selector的节点集合,采用的是深度优先预查找;如果没有匹配的,这个方法返回空集合) 这在BaseElement 为document的时候,没有什么问题,各浏览器的实现基本一致;但是,当BaseElement 为一个普通的dom Node的时候(支持这两个方法的dom Node ),浏览器的实现就有点奇怪了,举个例子: