DOM 选择器
· 阅读需 2 分钟
-
元素选择器
querySelector('div') -
ID 选择器
querySelector('#id') -
类选择器
querySelector('.myClass') -
属性选择器
querySelector('[data-id]')有 data-id 属性querySelector('[type="text"]')type 属性值为 textquerySelector('[href^="https"]')href 以 https 开头querySelector('[class*="btn"]')class 包含 btn
-
后代选择器
querySelector('div a') -
直接子元素选择器
querySelector('div > a') -
相邻兄弟选择器
querySelector('h1 + p')h1 之后相邻的 p 元素 -
伪类选择器
:first-child第一个子元素:last-child:nth-child(n)第 n 个子元素:nth-last-child(n):first-of-type第一个相同类型的子元素:last-of-type:nth-of-type(n):only-child唯一的子元素:only-of-type:hover:focus:active:checked:disabled:enabled:visited已访问的链接:not(selector)
-
复杂组合的案例
// 选择 class 为 container 的 div 中的所有选中的 checkbox
document.querySelectorAll('div.container input[type="checkbox"]:checked')
// 选择第一个 section 中的最后一个 p 标签
document.querySelector('section:first-of-type p: last-child')
// 选择不含 disabled 类的按钮
document.querySelectorAll('button:not(. disabled)')
// 选择所有偶数行的 tr
document.querySelectorAll('tr:nth-child(even)')