HTML - DOM 元素 matches() 方法



matches() 方法檢查元素是否匹配給定的 CSS 選擇器,如果匹配則返回 true,否則返回 false。

語法

element.matches(selectorString);

引數

引數 描述
selectorString 指定要測試的元素的 CSS 選擇器。

返回值

matches() 方法的返回值是布林值;如果元素匹配提供的 CSS 選擇器,則返回 true,否則返回 false。

HTML DOM 元素 'matches()' 方法示例

以下是 matches() 方法的一些示例,這些示例在 HTML DOM 元素中不同上下文中比較節點。

檢查 p 是否匹配選擇器

此示例演示如何使用 matches() 方法來檢查元素是否匹配提供的 CSS 選擇器。程式碼將 highlight 類新增到<p> 元素,從而更改其背景顏色。<span> 元素與選擇器不匹配,因此保持不變。

<!DOCTYPE html>
<html>
<head> 
    <style>
    .highlight {
        background-color: yellow;
    }
    </style>
</head>

<body>
    <h1>HTML - DOM Element</h1>
    <h2>matches() Method</h2>
    <p>It compares an element and applies styles 
        if they match...
    </p>
    
    <div id="container">
        <p>Hello, world!</p>
        <span>Not a paragraph</span>
    </div>
    <p>The <span> does not match p selector, 
        so no .highlight is added.
    </p>
    
    <script>
        // Select the <p> element inside #container
        const container = document.getElementById('container');
        const paragraph = container.querySelector('p');
    
        // Checks if paragraph matches the 'p' and adds highlight 
        if (paragraph.matches('p')) { 
            paragraph.classList.add('highlight');
        }
    </script>
</body>

</html>    

使用 'matches()' 進行按鈕高亮顯示

此示例演示 'matches()' 方法如何檢查被點選的元素是否匹配按鈕選擇器,並特別對按鈕應用高亮類。

<!DOCTYPE html>
<html>
<head> 
    <style>
        .highlight {
            background-color: lightgreen;
        }
    </style>
</head>

<body>
    <h1>HTML - DOM Element</h1>
    <h2>matches() Method</h2>
    <p> Highlights the button because the button 
        element matches the given CSS selector.
    </p>
    
    <div id="container">
        <button>Click Me</button>
        <p>Click target will be highlighted.</p>
    </div>
    
    <script>
        document.addEventListener('click', function(event) {
            if (event.target.matches('button')) {
                event.target.classList.add('highlight');
                const message = document.createElement('p');
                message.textContent = 'Button clicked: ' 
                + event.target.textContent;
                document.body.appendChild(message);
            }
        });
    </script>
</body>

</html>    

支援的瀏覽器

方法 Chrome Edge Firefox Safari Opera
matches() 支援 33 支援 15 支援 34 支援 7 支援 21
html_dom_element_reference.htm
廣告