HTML Element matches() Method: Matching Element Selector

The matches() method in the HTML DOM interface is a powerful tool for checking if an element would be selected by a specified CSS selector. This method allows you to programmatically determine whether an element matches a given selector string, providing a flexible way to apply conditional logic based on CSS rules directly in your JavaScript code. This guide provides a comprehensive overview of the matches() method, including its syntax, usage, and practical examples.

What is the matches() Method?

The matches() method is a feature of the Element interface in the DOM (Document Object Model). It takes a CSS selector string as its argument and returns a boolean value: true if the element would be selected by the selector, and false otherwise. This method is useful for tasks such as:

  • Applying specific behaviors to elements that match certain CSS rules.
  • Dynamically updating styles or attributes based on CSS selector matching.
  • Implementing custom filtering or selection logic based on CSS selectors.

Syntax of the matches() Method

The syntax of the matches() method is straightforward:

element.matches(selectorString);

Where:

  • element: The HTML element you want to test.
  • selectorString: A string containing the CSS selector to match against.

The selectorString can be any valid CSS selector, including:

  • Tag names (div, p, span)
  • Class names (.my-class)
  • IDs (#my-id)
  • Attribute selectors ([data-value="example"])
  • Pseudo-classes (:hover, :active)
  • Combinators (div > p, ul + li)

Practical Examples

Let’s explore several practical examples to illustrate how the matches() method can be used in different scenarios. Each example includes the necessary HTML and JavaScript code.

Basic Usage: Matching by Tag Name

This example demonstrates how to use the matches() method to check if an element is a paragraph (<p>) element.

<p id="paragraph1">This is a paragraph.</p>

<script>
  const paragraph1 = document.getElementById("paragraph1");
  const isParagraph = paragraph1.matches("p");
  console.log("Is paragraph1 a <p> element?", isParagraph); // Output: true
</script>

In this case, the matches() method checks if the paragraph1 element is a <p> element. Since it is, the method returns true.

Matching by Class Name

This example shows how to check if an element has a specific class name using the matches() method.

<div id="div1" class="my-class">This is a div with class 'my-class'.</div>

<script>
  const div1 = document.getElementById("div1");
  const hasMyClass = div1.matches(".my-class");
  console.log("Does div1 have the class 'my-class'?", hasMyClass); // Output: true
</script>

Here, the matches() method checks if the div1 element has the class my-class. Since it does, the method returns true.

Matching by ID

This example demonstrates how to check if an element has a specific ID using the matches() method.

<span id="span1">This is a span with ID 'span1'.</span>

<script>
  const span1 = document.getElementById("span1");
  const isSpan1 = span1.matches("#span1");
  console.log("Is the element span1?", isSpan1); // Output: true
</script>

In this case, the matches() method checks if the element is the one with the ID span1. Since it is, the method returns true.

Matching by Attribute

This example illustrates how to check if an element has a specific attribute and value using the matches() method.

<button id="button1" data-value="example">Click me</button>

<script>
  const button1 = document.getElementById("button1");
  const hasDataValue = button1.matches('[data-value="example"]');
  console.log("Does button1 have data-value='example'?", hasDataValue); // Output: true
</script>

Here, the matches() method checks if the button1 element has the attribute data-value with the value "example". Since it does, the method returns true.

Matching Pseudo-Classes

This example demonstrates how to check if an element would match a pseudo-class selector. Note that pseudo-class states (like :hover) are dynamic and depend on the current state of the element.

<style>
  #link1:hover {
    color: red;
  }
</style>
<a id="link1" href="#">Hover over me</a>

<script>
  const link1 = document.getElementById("link1");
  const wouldHover = link1.matches(":hover");
  console.log("Would link1 be red when hover?", wouldHover); // Output: false (initially)
</script>

The output of this example will initially be false because the element is not being hovered over when the script runs.

Complex Selector Matching

This example demonstrates how to use a more complex CSS selector to match an element.

<div id="container1">
  <p class="highlight">This is a highlighted paragraph.</p>
</div>

<script>
  const container1 = document.getElementById("container1");
  const paragraph2 = container1.querySelector(".highlight");
  const matchesSelector = paragraph2.matches("#container1 > .highlight");
  console.log(
    "Does the paragraph match '#container1 > .highlight'?",
    matchesSelector
  ); // Output: true
</script>

Here, the matches() method checks if the paragraph2 element matches the selector #container1 > .highlight, which means “an element with class highlight that is a direct child of the element with ID container1.” Since the paragraph meets this condition, the method returns true.

Use Case Example: Applying Styles Based on Selector Matching

Let’s create a practical example where we dynamically apply styles to elements based on whether they match a specific CSS selector.

<style>
  .special {
    font-weight: bold;
  }
</style>

<div id="elementContainer">
  <p class="item">Item 1</p>
  <p class="item special">Item 2</p>
  <p class="item">Item 3</p>
</div>

<script>
  const elementContainer = document.getElementById("elementContainer");
  const items = elementContainer.querySelectorAll(".item");

  items.forEach((item) => {
    if (item.matches(".special")) {
      item.style.color = "green";
    }
  });
</script>

In this example, we select all elements with the class item inside the elementContainer and then iterate through them. If an element also has the class special, we change its text color to green. This demonstrates how you can use the matches() method to conditionally apply styles based on CSS selector matching.

Browser Support

The matches() method is widely supported across modern browsers. Here’s a summary of browser compatibility:

  • Chrome: 34+
  • Edge: 14+
  • Firefox: 34+
  • Safari: 7.1+
  • Opera: 21+
  • IE: 9+

Given its broad support, you can confidently use the matches() method in your web development projects.

Polyfill for Older Browsers

For older browsers that do not support the matches() method natively, you can use a polyfill to provide the functionality. Here’s a simple polyfill:

if (!Element.prototype.matches) {
  Element.prototype.matches =
    Element.prototype.msMatchesSelector ||
    Element.prototype.webkitMatchesSelector;
}

This polyfill checks if the matches method is available and, if not, assigns it the value of msMatchesSelector (for Internet Explorer) or webkitMatchesSelector (for older versions of Chrome and Safari).

Conclusion

The matches() method is a valuable tool for programmatically determining whether an element matches a specific CSS selector. With its broad browser support and straightforward syntax, it provides a flexible way to implement conditional logic and dynamically update styles based on CSS rules. Whether you’re applying specific behaviors to elements that match certain CSS rules or implementing custom filtering logic, the matches() method offers a powerful and efficient solution.