To find the closest element to a target element in JavaScript, you can use the Element.closest()
method. This method traverses the element’s ancestors (including itself) in the DOM tree, searching for the closest element that matches a given selector.
// id
const targetElement = document.getElementById('target');
// class
const closestElement = targetElement.closest('.my-class');
// tag name
const closestElement = targetElement.closest('div');
// attribute
const closestElement = targetElement.closest('[data-attribute="value"]');
The above examples, targetElement
represents the element from which you want to find the closest element. You can modify the selector in the closest()
method to match your requirements. It can be a class, tag name, or attribute selector.
Get the closest sibling JavaScript example
Simple example code.
<!DOCTYPE html>
<html>
<head>
<title>Find Closest Element</title>
</head>
<body>
<div id="container">
<h2>Container Element</h2>
<div class="my-class">
<p>Target Element</p>
</div>
</div>
<script>
const targetElement = document.querySelector('p');
const closestElement = targetElement.closest('.my-class');
if (closestElement) {
console.log('Closest element found:', closestElement);
} else {
console.log('No closest element found.');
}
</script>
</body>
</html>
Output:
the Element.closest()
method only searches the ancestors (parent elements) of the given element. If you need to find the closest element including siblings, you can use a different approach by traversing the DOM manually.
Here’s an example that demonstrates how to find the closest element to a target selector, including siblings, in JavaScript:
HTML
<div id="container">
<h2>Container Element</h2>
<div class="my-class">
<p>Target Element</p>
</div>
<div class="my-class">
<p>Sibling Target Element</p>
</div>
</div>
JavaScript
const targetElement = document.querySelector('p');
const closestElement = findClosest(targetElement, '.my-class');
if (closestElement) {
console.log('Closest element found:', closestElement);
} else {
console.log('No closest element found.');
}
function findClosest(element, selector) {
let currentElement = element;
while (currentElement && !currentElement.matches(selector)) {
currentElement = currentElement.parentElement;
}
return currentElement;
}
When you run this code, you should see the closest element logged in the console, which in this case would be the first <div class="my-class">
element.
Do comment if you have any doubts or suggestions on this Js code.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version