matches メソッドは、要素が指定した CSS セレクタにマッチするかどうかをチェックして、true または false を返します。条件分岐でとても便利なメソッドです。
基本的な使い方
element.matches(selector) で、その要素がセレクタに合致するかを判定します。
<button class="btn primary">送信</button>
const btn = document.querySelector('button'); console.log(btn.matches('.btn')); // true console.log(btn.matches('.primary')); // true console.log(btn.matches('.secondary')); // false console.log(btn.matches('button')); // true console.log(btn.matches('button.btn')); // true
イベント処理での活用
クリックされた要素が特定の条件を満たすかどうかをチェックするのに使えます。
document.addEventListener('click', function(e) { if (e.target.matches('a.external')) { console.log('外部リンクがクリックされました'); } if (e.target.matches('button[type="submit"]')) { console.log('送信ボタンがクリックされました'); } });
実際に動かしてみよう
ボタンの種類によって処理を分岐させます。
HTML
CSS
JavaScript
<button class="btn save">保存</button> <button class="btn cancel">キャンセル</button> <p id="result">ボタンをクリックしてください</p>
document.addEventListener('click', function(e) { const result = document.getElementById('result'); if (e.target.matches('.save')) { result.textContent = '保存ボタンが押されました'; result.style.color = 'green'; } if (e.target.matches('.cancel')) { result.textContent = 'キャンセルボタンが押されました'; result.style.color = 'red'; } });
matches と closest の使い分け
matches
その要素自身がセレクタにマッチするかをチェック
closest
その要素または祖先にマッチする要素があるかを探す
例えば、ボタンの中にアイコンがある場合:
<button class="delete"> <span class="icon">×</span> </button>
document.addEventListener('click', function(e) { // icon をクリックしても button を検出したいなら closest if (e.target.closest('.delete')) { console.log('削除ボタンがクリックされた'); } // まさに .delete 要素自身がクリックされたかをチェックするなら matches if (e.target.matches('.delete')) { console.log('.delete 要素そのものがクリックされた'); } });
matches は要素の判定、closest は親方向への探索、と覚えておきましょう。