JavaScript Element.closest()

Samuel DeSantis
3 min readFeb 23, 2022

Summary: I will try to provide a brief overview of closest() and provide an example that I think helps show when it can be useful.

According to MDN Web Docs:

The closest() method traverses the Element and its parents (heading toward the document root) until it finds a node that matches the provided selector string. Will return itself or the matching ancestor. If no such element exists, it returns null.

My interpretation of this is that closest() basically ‘looks’ for a node that seems to have the matching characteristics as requested in the argument for the function. As seen in the example below, I use closest to find the nearest button to make a change to the color.

For this example I set up a 3x3 grid of buttons and the goal is to be able to toggle the button color between black and red. The following figure shows the nine buttons that will be used in the matrix and I add the styling of background-color: black . Don’t forget to add the styling and JavaScript files!

Figure 1: index.html

Once the HTML is setup, then I went ahead and set up the 3x3 matrix with CSS Grid and added very minimal styling.

Figure 2: style.css

Once the HTML & CSS are setup then webpage should look like the following:

Figure 3: Webpage with HTML & CSS

From here we have the basic setup, but now we want to implement the color change on click. To do that we want to setup an event listener and listen for button pushes.

So, first we add an event listener to the document and want to listen for a click event (see here for other mouse events). Next, we can use closest() on the event target and store that in a variable we call cell . The closest function here returns the first node that matches the argument provided to closest() , which is the button you click. Go ahead and add console.log(cell) after the variable initialization and add some unique text to the buttons so you can see which button is logged. After that it’s some basic logic to toggle back and forth between colors. So now you should be able to click on the different cells and change their colors between black and red. Another fun thing you can do is change "click" to "mouseover" so that when you simply mouseover the cells they change color. It reminds me of a simple way to make like a scary maze game type thing.

I hope this is helpful to someone! If anyone has any critiques or suggestions for using closest() feel free to share!

-Samuel DeSantis

--

--