关于使用querySelector方法的介绍

关于querySelector可能让你意外的特性:http://www.zhangxinxu.com/wordpress/2015/11/know-dom-queryselectorall/ 
 
document.querySelector("body");//返回body节点
document.querySelector("#k");//返回id为k的节点
document.querySelector("#k span");//返回id为k的节点下的第一个span节点
document.querySelector("#k").querySelector("span");//返回id为k的节点下的第一个span节点
document.querySelectorAll("li");//返回所用tagName为li的节点集合(NodeList)
document.querySelectorAll("div .li");//返回class为li的div
 
但需要注意的是返回的NodeList集合中的元素是非实时的,所谓实时的就是动态添加新元素后会实时更新NodeList集合,而非实时则不会更新。
总结 :
1.得到的元素不是需要很麻烦的多次getElementBy..的话,尽量使用getElementBy..,因为他快些。
2.得到的元素需要很麻烦的多次getElementBy..组合才能得到的话使用querySelector,方便。
3.看实际情况,你决定方便优先还是性能优先。
posted @ 2015-04-12 17:49  前端丶守望者  阅读(2039)  评论(0编辑  收藏  举报