selectors选择器
Basic jQuery to DOM API examples
More advanced jQuery to DOM API examples
介绍 (Introduction)
jQuery and other DOM libraries got a huge popularity boost in the past, among with the other features they provided, thanks to an easy way to select elements on a page.
jQuery和其他DOM库在过去得到了极大的普及,其中包括它们提供的其他功能,这要归功于一种在页面上选择元素的简便方法。
Traditionally browsers provided just a single way to select a DOM element - by its id
attribute, with getElementById()
, a method offered by the document
object.
传统上,浏览器仅提供一种选择DOM元素的方法-通过其id
属性,使用由document
对象提供的方法getElementById()
。
选择器API (The Selectors API)
Since 2013 the Selectors API, the DOM allows you to use two more useful methods:
从2013年开始, Selectors API便可以使用DOM使用两种更有用的方法:
document.querySelector()
document.querySelector()
document.querySelectorAll()
document.querySelectorAll()
They can be safely used, as caniuse.com tells us, and they are even fully supported on IE9 in addition to all the other modern browsers, so there is no reason to avoid them, unless you need to support IE8 (which has partial support) and below.
正如caniuse.com告诉我们的那样 ,可以安全地使用它们,并且除所有其他现代浏览器之外,它们甚至在IE9上也得到完全支持,因此没有理由避免使用它们,除非您需要支持IE8(部分支持) )及以下。
They accept any CSS selector, so you are no longer limited by selecting elements by id
.
它们接受任何CSS选择器,因此不再受id
选择元素的限制。
document.querySelector()
returns a single element, the first founddocument.querySelector()
返回单个元素,第一个找到document.querySelectorAll()
returns all the elements, wrapped in a NodeList object.document.querySelectorAll()
返回包装在NodeList对象中的所有元素。
These are all valid selectors:
这些都是有效的选择器:
document.querySelector('#test')
document.querySelector('#test')
document.querySelector('.my-class')
document.querySelector('.my-class')
document.querySelector('#test .my-class')
document.querySelector('#test .my-class')
document.querySelector('a:hover')
document.querySelector('a:hover')
从jQuery到DOM API的基本示例 (Basic jQuery to DOM API examples)
Here below is a translation of the popular jQuery API into native DOM API calls.
下面是流行的jQuery API到本地DOM API调用的转换。
按id
选择 (Select by id
)
$('#test')
document.querySelector('#test')
We use querySelector
since an id
is unique in the page
我们使用querySelector
因为id
在页面中是唯一的
按class
选择 (Select by class
)
$('.test')
document.querySelectorAll('.test')
按标签名称选择 (Select by tag name)
$('div')
document.querySelectorAll('div')
jQuery到DOM API的更高级示例 (More advanced jQuery to DOM API examples)
选择多个项目 (Select multiple items)
$('div, span')
document.querySelectorAll('div, span')
按HTML属性值选择 (Select by HTML attribute value)
$('[data-example="test"]')
document.querySelectorAll('[data-example="test"]')
通过CSS伪类选择 (Select by CSS pseudo class)
$(':nth-child(4n)')
document.querySelectorAll(':nth-child(4n)')
选择元素的后代 (Select the descendants of an element)
For example all li
elements under #test
:
例如#test
下的所有li
元素:
$('#test li')
document.querySelectorAll('#test li')
selectors选择器