JavaScript closest() Method Tutorial

In this section, we will learn what the Element closest() method is and how to use it in JavaScript.

What is Element closest() Method in JavaScript?

The JavaScript Element closest() method is used to search the ancestors of an element and get a reference to an element that matches a CSS selector.

For example, let’s say you’ve called this method using a <p> element in an HTML document. Now this method will start with the element that invoked this method and compare the CSS selector (the argument of this method) with the element itself to see if they match or not.

If not, then this method goes to the parent element and compares that one with the specified CSS selector as well.

This process goes on until one of the ancestor elements matches the CSS selector (the argument of the method) or if none of them matched the argument, a null value will return instead.

Element closest() Method Syntax:

element.closest(CSS-selector);

Element closest() Method Parameter

The method takes one argument and that is a CSS-selector query.

Element closest() Method Return Value

The return value of this method is a reference to an element that matched the target CSS selector (the argument of the method).

Note: the null value will return if no element matched the specified requirement.

Example: JavaScript parent element

See the Pen JavaScript parent element by Omid Dehghan (@odchan1) on CodePen.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies