querySelector与querySelectorAll的用法

DOM API querySelector与querySelectorAll的用法:  http://www.qttc.net/201309371.html

querySelectorAll与querySelector的区别是querySelectorAll找出所有匹配的节点并返回数组,querySelector找到一个后就返回节点对象。

找出所有标签 

document.querySelectorAll("*")

找出head下所有的标签 

document.head.querySelectorAll("*")

找出body标签下的第一个div标签

document.body.querySelectorAll("div")[0]
document.body.querySelector("div")

找出所有class=box的标签 

document.querySelectorAll(".box")

找出所有class=boxdiv标签 

document.querySelectorAll("div.box")

找出所有id=lost的标签 

document.querySelectorAll("#lost")

找出所有p标签并且id=lost的标签 

document.querySelectorAll("p#lost")

找出所有name=qttc的标签 

document.querySelectorAll("*[name=qttc]")

找出所有存在name属性的标签

 document.querySelectorAll("*[name]")

 document.querySelectorAll("p.hot[name]")

 document.querySelectorAll("p[class=hot][name]")

在 document 中选取 class 为 test 的 div 的子元素 p 的第一个子元素 

document.querySelector("div.test>p:first-child");

document.querySelectorAll("div.test>p:first-child")[0];

使用 querySelectorAll 给所有 class 为 emphasis 的元素加粗显示

varemphasisText = document.querySelectorAll(".emphasis");

for( vari = 0 , j = emphasisText.length ; i < j ; i++ )

{

         emphasisText[i].style.fontWeight = "bold";

}
document.querySelector('button').addEventListener('click', function(){ 
    logger.updateCount(); 
}); 
原文地址:https://www.cnblogs.com/zgxblog/p/11661852.html