HTML DOM matches() Method
Example
Determine whether an element matches a CSS selector:
var element = document.getElementById("myElement");
if (element.matches(".container")) {
element.innerHTML = "This element matches the \".container\" CSS selector";
} else {
element.innerHTML = "This element does not match the \".container\" CSS selector";
}
Try it Yourself »Definition and Usage
The matches()
method returns a Boolean value indicating whether an element
is matched by a specific CSS selector or not.
Tip: For a list of all CSS Selectors, look at our CSS Selectors Reference.
Browser Support
The numbers in the table specify the first browser version that fully supports the method.
Method | |||||
---|---|---|---|---|---|
matches() | 33.0 | 18.0 | 34.0 | 7.0 | 21.0 |
Syntax
element.matches(selectors)
Parameter Values
Parameter | Description |
---|---|
selectors |
Required. Specifies one or more CSS selectors to match the element. These are used to select HTML elements based on their id, classes, types, attributes, values of attributes, etc. For multiple selectors, separate each selector with a comma. The returned element depends on which element that is first found in the document (See "More Examples"). Tip: For a list of all CSS Selectors, look at our CSS Selectors Reference. |
Technical Details
Return Value: |
A Boolean, indicating whether the element can be matched by the CSS selector:
|
---|
More Examples
Example
Find out if an element matches one of multiple selectors:
var element = document.getElementById("myElement");
if (element.matches(".container, .wrapper")) {
element.innerHTML = "This element matches either the \".container\" CSS selector or the \".wrapper\" selector.";
} else {
element.innerHTML = "This element does not match any of the selectors.";
}
Try it Yourself »Related Pages
JavaScript Reference: The element.closest() method.