简介:

document.querySelector() 是 JavaScript 中用于在 HTML 文档中查找元素的 DOM 方法。它通过 CSS 选择器定位元素,并返回第一个匹配的节点。如果未找到匹配项,则返回 null


语法

const element = document.querySelector("CSS选择器");

核心特点

  1. 仅返回第一个匹配项:即使有多个元素符合条件,也只返回第一个。

  2. 支持复杂选择器:可以使用类、ID、属性、伪类等任何有效的 CSS 选择器。

  3. 作用范围灵活:不仅可以在 document 上调用,也可以在任意元素上调用,限制搜索范围为该元素的子节点。


常见用法示例

1. 按 ID 查找
const header = document.querySelector("#header"); // 查找 ID 为 "header" 的元素
2. 按类名查找
const btn = document.querySelector(".btn-primary"); // 查找第一个类名包含 "btn-primary" 的元素
3. 按标签名查找
const firstImg = document.querySelector("img"); // 查找第一个 <img> 标签
4. 组合选择器
const item = document.querySelector("ul.menu > li.active"); 
// 查找类为 "menu" 的 <ul> 下的第一个类为 "active" 的 <li>
5. 属性选择器
const link = document.querySelector("a[target='_blank']"); 
// 查找第一个带有 `target="_blank"` 的 <a> 标签
6. 伪类选择器
const firstInput = document.querySelector("input:first-of-type"); 
// 查找同层级中的第一个 <input>

对比其他方法

方法 返回值 是否动态更新 选择器类型
querySelector() 第一个元素 CSS 选择器
querySelectorAll() 所有元素集合 CSS 选择器
getElementById() 单个元素 ID
getElementsByClassName() HTML集合 类名
Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐