Borislav Hadzhiev
Last updated: Jul 23, 2022
Check out my new book
Use the closest()
method to get the closest parent element by tag, e.g.
child.parentElement.closest('div')
. The closest()
method traverses the
Element
and its parents until it finds a node that matches the provided
selector.
Here is the HTML for the examples in this article.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="parent-1"> <span id="parent-2"> <div id="child">Child 1</div> </span> </div> <script src="index.js"></script> </body> </html>
And here is the related JavaScript code.
const child = document.getElementById('child'); // ✅ Gets immediate parent, regardless which Tag const immediateParent = child.parentElement; console.log(immediateParent); // 👉️ span#parent-2 // ✅ Gets a parent that is a `div` element const parent = child.parentElement.closest('div'); console.log(parent); // 👉️ div#parent-1
We used the Node.parentElement property to get the DOM node's immediate parent element.
However, the parentElement
property doesn't allow us to filter the results as
it returns the parent element.
We used the closest method to get the closest parent element by tag.
parentElement
property on the child
before calling the closest()
method is because the closest()
method traverses the Element
and its parents until it finds a node that matches the provided selector string.In our case, the child is a div
element and the parent we want access to is a
div
, so calling the closest()
method and passing it a div
selector returns
the child element.
parentElement
property, we start traversing the DOM for an element that matches the selector from the parent element onwards.If no element matches the selector, the closest()
method returns null
.
The method takes a string that contains a selector. The provided selector can be as specific as necessary.
const child = document.getElementById('child'); // ✅ Gets a parent that is a `div` element const parent = child.parentElement.closest('body > div'); console.log(parent); // 👉️ div#parent-1
The example above selects a div
element that has the body
element as its
parent.
closest()
method, a SyntaxError
is thrown.