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.
targetElement.closest(selectors)
selector
: This is a DOMString
containing a selector list.
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()
.
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) DIV
element.
In line 13, we have the first child DIV
element of the above DIV
element. It is the parent for the below div
element.
In line 14, we have the child element of the above div
, which has an ID elem
, which we will use to get the element object.
In line 19, to get the DIV child element with id elem
, we use document.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 if
condition, checking if the method closest()
has returned the parent element or not. If true, then we apply the style
property on the parent element.
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.
RELATED TAGS
CONTRIBUTOR
View all Courses