查询选择器

在现代浏览器 [1]中 ,可以使用类似 CSS 的选择器来查询文档中的元素 - 与 sizzle.js (由 jQuery 使用)相同。

querySelector

返回文档中与查询匹配的第一个 Element 。如果没有匹配,则返回 null

// gets the element whose id="some-id"
var el1 = document.querySelector('#some-id');
 
// gets the first element in the document containing "class-name" in attribute class
var el2 = document.querySelector('.class-name');
 
// gets the first anchor element in the document
var el2 = document.querySelector('a');
 
// gets the first anchor element inside a section element in the document
var el2 = document.querySelector('section a');

querySelectorAll

返回包含文档中与查询匹配的所有元素的 NodeList 。如果没有匹配,则返回空的 NodeList

// gets all elements in the document containing "class-name" in attribute class
var el2 = document.querySelectorAll('.class-name');
 
// gets all anchor elements in the document
var el2 = document.querySelectorAll('a');

// gets all anchor elements inside any section element in the document
var el2 = document.querySelectorAll('section a');