ZetCode

JavaScript querySelector

最后修改于 2025 年 4 月 2 日

在本文中,我们将探讨 JavaScript 中的 element.querySelector 方法。这个强大的方法允许开发人员使用 CSS 选择器查找元素,提供了灵活的 DOM 元素选择功能。

基本定义

querySelector 方法返回在文档或其被调用的元素内与指定 CSS 选择器匹配的第一个元素。它是现代 DOM API 的一部分,并且在所有现代浏览器中都有效。

getElementById 不同,querySelector 可以使用任何 CSS 选择器查找元素,包括类、属性、伪类和复杂的选择器组合。如果找不到匹配项,它将返回 null。

基本的 querySelector

此示例演示了如何使用 querySelector 按类选择元素。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Basic querySelector</title>
</head>
<body>

<div class="content">Hello there!</div>

<script>
    const element = document.querySelector('.content');
    console.log(element.textContent);
</script>

</body>
</html>

在这个基本示例中,我们使用 CSS 类选择器语法(.)来选择具有 "content" 类的 div 元素。该方法返回第一个匹配的元素,然后我们将其记录到控制台。

这展示了 querySelector 与类选择器的基本用法。该方法用途广泛,可以作用于任何元素或文档。

选择嵌套元素

此示例展示了如何使用 querySelector 查找 DOM 中的嵌套元素。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Nested Elements</title>
</head>
<body>

<div id="container">
    <p class="message">This is a message inside the container</p>
</div>

<script>
    const container = document.querySelector('#container');
    const message = container.querySelector('.message');
    console.log(message.textContent);
</script>

</body>
</html>

在这里,我们首先按 ID 选择容器 div,然后在该元素上使用 querySelector 来查找带有 "message" 类的段落。这表明 querySelector 可以被限定在 DOM 的特定部分。

将查询限定在特定容器可以提高性能,并通过限制搜索区域使代码更易于维护。这种模式在基于组件的体系结构中很常见。

属性选择器

此示例演示了如何使用属性选择器来查询。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Attribute Selectors</title>
</head>
<body>

<input type="text" data-role="search" placeholder="Search...">
<button onclick="findInput()">Find Input</button>

<script>
    function findInput() {
        const searchInput = document.querySelector('[data-role="search"]');
        searchInput.style.border = '2px solid red';
    }
</script>

</body>
</html>

在此示例中,我们使用属性选择器来查找具有特定 data-role 属性的 input 元素。当单击按钮时,input 的边框将进行样式设置以突出显示它。

属性选择器对于根据自定义数据属性或特定属性值选择元素非常强大。它们在现代 Web 框架和库中很常用。

组合选择器

此示例展示了如何组合多个选择器以实现更精确的定位。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Combined Selectors</title>
</head>
<body>

<ul class="menu">
    <li>Item 1</li>
    <li class="active">Item 2</li>
    <li>Item 3</li>
</ul>

<script>
    const activeItem = document.querySelector('ul.menu li.active');
    activeItem.style.fontWeight = 'bold';
    console.log('Active item:', activeItem.textContent);
</script>

</body>
</html>

在这里,我们组合了元素、类和后代选择器,以专门定位活动菜单项。选择器字符串匹配一个带有 "active" 类的 li,该 li 是带有 "menu" 类的 ul 的后代。

组合选择器允许非常精确地定位元素,而无需添加过多的 ID 或类。这使得 HTML 更干净,同时保持选择的特异性。

伪类选择器

此示例演示了如何使用伪类选择器来查询。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Pseudo-class Selectors</title>
</head>
<body>

<form>
    <input type="text" required placeholder="Required field">
    <input type="text" placeholder="Optional field">
    <button type="submit">Submit</button>
</form>

<script>
    const requiredField = document.querySelector('input:required');
    requiredField.style.backgroundColor = '#fff9e6';
    
    const submitButton = document.querySelector('form button:last-child');
    submitButton.addEventListener('click', () => {
        alert('Form submitted!');
    });
</script>

</body>
</html>

在此示例中,我们使用 :required 伪类来为必填表单字段设置不同的样式,并使用 :last-child 伪类来定位提交按钮。伪类提供了动态选择功能。

伪类选择器对于根据元素的 DOM 状态或位置进行定位非常强大。它们常用于表单验证和交互式 UI 元素。

来源

MDN querySelector 文档

在本文中,我们展示了如何在 JavaScript 中使用 querySelector 及其各种选择器类型。该方法对于现代 DOM 操作至关重要,并提供了灵活的元素选择功能。

作者

我的名字是 Jan Bodnar,我是一名充满热情的程序员,拥有丰富的编程经验。我从 2007 年开始撰写编程文章。至今,我已撰写了 1400 多篇文章和 8 本电子书。我在编程教学方面拥有十多年的经验。

列出 所有 JS DOM 教程