How to use the HTML closest() method
Overview
In this shot, we will learn how to get the closest parent of an element with a specified CSS selector as a parameter.
We will use the closest() method, which will return us the closest parent element with the specified CSS selector passed as a parameter in the method.
Syntax
targetElement.closest(selectors)
Parameters
selector: This is a DOMString containing a selector list.
Example
Let’s try to understand how this works. We will create two parents with the same class and check that only the closest parent is returned by the method closest().
Code explanation
-
In line 5, we have a CSS property for the class
test, where we defined a property background color. -
In line 12, we have the first parent (grandparent)
DIVelement. -
In line 13, we have the first child
DIVelement of the aboveDIVelement. It is the parent for the belowdivelement. -
In line 14, we have the child element of the above
div, which has an IDelem, which we will use to get the element object. -
In line 19, to get the DIV child element with id
elem, we usedocument.getElementById()and store the object in the variable. -
In line 20, we use the method
closest()with the class name.test, which returns the closest parent element with the class matching with.test. -
In line 21, we use the
ifcondition, checking if the methodclosest()has returned the parent element or not. If true, then we apply thestyleproperty on the parent element.
Output
We have seen in the output that the grandparent and parent have a similar class test. The closest() method returns the first closest parent, not the grandparent, and the order style is only applied to the parent, not the grandparent.