YouTip LogoYouTip

Met Element Matches

# HTML DOM Element matches() Method The `matches()` method of the `Element` interface checks whether the element would be selected by the specified CSS selector string. This method is highly efficient for event delegation, DOM traversal, and validating elements against dynamic criteria without having to perform manual property checks. --- ## Definition and Usage The `matches()` method returns a boolean value: * **`true`** if the element matches the specified CSS selector(s). * **`false`** if the element does not match. --- ## Syntax ```javascript let result = element.matches(selectors); ``` ### Parameters | Parameter | Type | Description | | :--- | :--- | :--- | | `selectors` | *String* | **Required.** A valid CSS selector string (e.g., `".class-name"`, `"#id"`, `"div > p"`). You can also pass multiple selectors separated by commas (e.g., `".container, .wrapper"`). | ### Return Value | Type | Description | | :--- | :--- | | `Boolean` | Returns `true` if the element matches the selector(s); otherwise, returns `false`. | ### Exceptions * **`SyntaxError`**: Thrown if the specified `selectors` string is not a valid CSS selector. --- ## Code Examples ### Example 1: Basic Class Matching Check if an element has a specific class name. ```javascript // Select the element const element = document.getElementById("demo"); // Check if the element matches the class ".container" let isContainer = element.matches(".container"); console.log(isContainer); // Returns true or false ``` ### Example 2: Matching Multiple Selectors You can pass a comma-separated list of selectors. The method returns `true` if the element matches **at least one** of the selectors. ```javascript // Select the element const element = document.getElementById("demo"); // Check if the element matches either ".container" OR ".wrapper" let matchesEither = element.matches(".container, .wrapper"); console.log(matchesEither); // Returns true or false ``` ### Example 3: Practical Use Case (Event Delegation) The `matches()` method is extremely useful when implementing event delegation, allowing you to filter target elements dynamically. ```javascript document.getElementById("parent-list").addEventListener("click", function(event) { // Check if the clicked element is an active list item if (event.target.matches("li.active")) { console.log("An active list item was clicked!"); // Perform action... } }); ``` --- ## Browser Support The `matches()` method is widely supported across all modern browsers: | Chrome | Edge | Firefox | Safari | Opera | | :---: | :---: | :---: | :---: | :---: | | 33+ | 15+ | 34+ | 7.1+ | 21+ | *Note: Older browsers (like Internet Explorer 9-11) supported this method under non-standard prefixed names such as `msMatchesSelector()`, `webkitMatchesSelector()`, or `mozMatchesSelector()`. Modern applications targeting up-to-date browsers do not need these prefixes.*
← Bootstrap5 FormsProp Element Lastelementchild β†’