ZetCode

JavaScript element.matches()

最后修改于 2025 年 4 月 2 日

在本文中,我们将探讨 JavaScript 中的 element.matches() 方法。此方法检查一个元素是否与特定的 CSS 选择器匹配,这对于 DOM 遍历和事件委托非常有用。

基本定义

element.matches() 方法返回一个布尔值,指示该元素是否会根据指定的 CSS 选择器字符串被选中。它是 Element API 的一部分,并在所有现代浏览器中得到支持。

此方法对于事件委托特别有用,您需要检查事件目标是否满足某些条件。它可以接受任何有效的 CSS 选择器作为参数,包括复杂的选择器。

基本的 element.matches()

此示例演示了 matches() 检查元素类型的基本用法。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Basic matches()</title>
</head>
<body>

<div id="content">Hello there!</div>
<p class="message">This is a message.</p>

<script>
    const div = document.getElementById('content');
    const p = document.querySelector('.message');
    
    console.log(div.matches('div')); // true
    console.log(div.matches('#content')); // true
    console.log(p.matches('div.message')); // false
</script>

</body>
</html>

在此基本示例中,我们检查元素是否与不同的选择器匹配。div 元素同时匹配 'div' 和 '#content' 选择器,而段落元素不匹配不存在的 'div.message' 选择器。

这演示了 matches() 验证元素-选择器关系的根本用法。只有当元素能被给定的 CSS 选择器选中时,该方法才返回 true。

使用 matches() 进行事件委托

此示例展示了如何使用 matches() 进行高效的事件委托。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Event Delegation</title>
</head>
<body>

<ul id="menu">
    <li class="item">Home</li>
    <li class="item active">Products</li>
    <li class="item">About</li>
</ul>

<script>
    document.getElementById('menu').addEventListener('click', function(e) {
        if (e.target.matches('li.item')) {
            console.log('Menu item clicked:', e.target.textContent);
        }
        
        if (e.target.matches('li.active')) {
            console.log('Active item clicked!');
        }
    });
</script>

</body>
</html>

在这里,我们在菜单列表上使用事件委托。点击处理程序使用 matches() 检查目标是否与特定的选择器匹配。这种方法比单独将处理程序附加到每个项目更有效。

该示例展示了 matches() 如何实现基于元素特性的选择性事件处理。它可以与单个和多个类选择器一起使用。

检查复杂选择器

此示例演示了 matches() 与复杂的 CSS 选择器组合。

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

<div class="container">
    <p class="highlight">Important text</p>
    <p>Normal text</p>
    <a href="#" class="btn highlight">Button</a>
</div>

<script>
    const elements = document.querySelectorAll('.container *');
    
    elements.forEach(el => {
        if (el.matches('p.highlight')) {
            console.log('Highlighted paragraph:', el.textContent);
        }
        
        if (el.matches('a.btn')) {
            console.log('Button element found');
        }
        
        if (el.matches(':not(.highlight)')) {
            console.log('Element without highlight:', el.tagName);
        }
    });
</script>

</body>
</html>

此示例展示了 matches() 如何处理复杂的选择器。我们检查具有多个类、特定组合和否定伪类的元素。

该方法处理所有 CSS 选择器类型,包括属性选择器、伪类和组合子。这使其在精确的元素选择检查方面非常强大。

动态类检查

此示例演示了使用 matches() 检查动态添加的类。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Dynamic Classes</title>
    <style>
        .active { color: red; }
        .hidden { display: none; }
    </style>
</head>
<body>

<div id="box" class="box">Sample Content</div>
<button onclick="toggleClass()">Toggle Active</button>
<button onclick="checkStatus()">Check Status</button>

<script>
    const box = document.getElementById('box');
    
    function toggleClass() {
        box.classList.toggle('active');
    }
    
    function checkStatus() {
        const isActive = box.matches('.active');
        console.log('Is box active?', isActive);
    }
</script>

</body>
</html>

在这里,我们切换元素上的一个类,并使用 matches() 检查其当前状态。该方法提供了一种干净的方法来验证类的存在,而无需直接访问 classList。

当您需要检查复杂的选择器条件,而不仅仅是类的存在时,这种方法很有用。它可以与任何有效的 CSS 选择器一起使用,而不仅仅是类选择器。

使用 matches() 进行表单验证

此示例展示了如何使用 matches() 进行表单验证模式。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Form Validation</title>
</head>
<body>

<form id="userForm">
    <input type="text" id="username" 
           pattern="[A-Za-z]{3,}" 
           title="3+ letters" 
           required>
    <button type="submit">Submit</button>
</form>
<p id="message"></p>

<script>
    document.getElementById('userForm').addEventListener('submit', function(e) {
        e.preventDefault();
        const input = document.getElementById('username');
        const message = document.getElementById('message');
        
        if (input.matches(':invalid')) {
            message.textContent = 'Please enter a valid username (3+ letters)';
            message.style.color = 'red';
        } else {
            message.textContent = 'Form submitted successfully!';
            message.style.color = 'green';
        }
    });
</script>

</body>
</html>

在此表单验证示例中,我们使用 matches() 和 ':invalid' 伪类来检查输入的有效性。这种方法与 HTML5 验证属性(如 'pattern' 和 'required')集成。

该示例演示了 matches() 如何与反映元素状态的伪类一起工作。这为检查验证状态提供了一种声明式的方法。

来源

MDN element.matches() 文档

在本文中,我们展示了如何在 JavaScript 中使用 element.matches()。此方法对于现代 Web 开发中的 DOM 遍历、事件委托和选择器匹配至关重要。

作者

我叫 Jan Bodnar,我是一名充满热情的程序员,拥有丰富的编程经验。我从 2007 年开始撰写编程文章。到目前为止,我已撰写了 1400 多篇文章和 8 本电子书。我在教授编程方面拥有超过十年的经验。

列出 所有 JS DOM 教程