HTML - DOM Element closest() Method



The HTML DOM Element closest() method is used to find (get) the nearest ancestor (predecessor) element that matches a specified selector. The term ancestor refers to the "parent", "grandparent", or any "higher-level" element of the current element.

This method returns the closest ancestor of the current element (or the current element itself) that matches a given CSS selector.

Note: If no such ancestor exists, it returns null. If the selector is invalid, it will throw a SYNTAX_ERR error.

Syntax

Following is the syntax of the HTML DOM Element closest() method −

element.closest(selectors);

Parameters

This method accepts a single parameter as mentioned below −

Method Description
selectors A string of one or more CSS selectors.

Return Value

This method returns the closest ancestor element object that matches the specified selector.

Example 1: Finding the Closest Ancestor (Predecessor)

The following program demonstrates the usage of the HTML DOM Element closest() method by retrieving the nearest ancestor element of a given selector −

<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML DOM Element closest()</title>
<style>
   .parent {
       border: 2px solid #ccc; 
       margin: 10px; 
       padding: 4px;
   }
   .highlight {
       background-color: yellow;
   }
   .grandparent{
       border: 2px solid;
   }
   .ch{
       border: 2px solid;
       padding: 4px;
   }
</style>
</head>
<body>
<h3>HTML DOM Element closest() Method</h3>
<p>Click button and highlight the closest parent.</p>
<div class="grandparent">
   Grandparent
   <div class="parent">
      Parent
      <div class="ch" id="Ele">
         Target Element
      </div>
   </div>
</div>
<br>
<button onclick="highlightClosest()">Highlight Closest Parent</button>
<script>
   function highlightClosest() {
      const closestParent = 
	  document.getElementById('Ele').closest('.parent');
      closestParent.classList.add('highlight');
   }
</script>
</body>
</html>        

When the button clicks, the closest parent will be highlighted with a yellow background.

Example 2: Finding Closest Element

Here is another example of the HTML DOM Element closest() method. We use this method to find the close element from the wrapper class −

<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML DOM Element closest() Method</title>
<style>
   .container, .wrapper {
      padding: 10px;
      text-align: center;
   }
   .child { 
      background-color: lightblue;
   }
   .highlight {
      background-color: red !important;
   }
</style>
</head>
<body>
<h3>HTML DOM Element closest() Method</h3>
<p>Finds closest element within 'wrapper' class.</p>
<div class="wrapper">
   <div class="child" id="Ele">Target Element</div>
</div>
<div class="container">
   <div class="child">Another Target Element</div>
</div>
<button onclick="highlightClosest()">Highlight Closest .wrapper</button>
<script>
   function highlightClosest() {
      const element=document.getElementById('Ele');
      const closestContainerOrWrapper = 
	  element.closest('.container, .wrapper'); 
      closestContainerOrWrapper.classList.add('highlight');
   }
</script>
</body>
</html>

The above program highlights the closest element with a red background.

Example 3: Handling Syntax Error

If the selector is invalid, it will throw a SYNTAX_ERR error −

<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML DOM Element closest() Method</title>
<style>
   .container, .wrapper {
      padding: 10px;
      text-align: center;
      padding: 10px;
   }
   .child { 
      background-color: rgb(16, 176, 120);
      padding: 10px;
   }
   .highlight {
      background-color: red !important;
   }
   button{
    padding: 10px;
   }
</style>
</head>
<body>
<h3>HTML DOM Element closest() Method</h3>
<p>Finds closest element within 'wrapper' class.</p>
<div class="wrapper">
   <div class="child" id="Ele">Target Element</div>
</div>
<div class="container">
   <div class="child">Another Target Element</div>
</div>
<button onclick="highlightClosest()">Find closest</button>
<p id="result"></p>
<script>
   function highlightClosest() {
      const element = document.getElementById('Ele');
      try {
         const closestInv = element.closest('.container, !invalid-selector');
         closestInv.classList.add('highlight');
      } catch (e) {
         document.getElementById('result').textContent = `Error: ${e}`;
      }
   }
</script>
</body>
</html>

The above program throws the "Error: SyntaxError: Failed to execute 'closest' on 'Element': '.container, !invalid-selector' is not a valid selector.".

Supported Browsers

Method Chrome Edge Firefox Safari Opera
closest() Yes 41.0 Yes 15.0 Yes 35.0 Yes 9.0 Yes 28.0
html_dom.htm
Advertisements