# .closest()

> The `.closest()` JS browser API method returns the element itself or its closest ancestor that matches the specified CSS selector.

## How do I find the closest parent element matching a selector?

The browser API method that returns the element itself or its nearest ancestor matching a given CSS selector, or `null` if none match. It's often used in event delegation to find the clicked item from `event.target`.

- Topic: Object on Page
- Type: method
- Browser support: Chrome 41+, Chrome Android 41+, Edge 15+, Firefox 35+, Firefox Android 35+, Safari 6+, Safari iOS 9+

## Example

Wrong:

```js
list.addEventListener('click', (e) => {
  if (e.target.matches('button')) remove(e.target);
});
```

Right:

```js
list.addEventListener('click', (e) => {
  const btn = e.target.closest('button');
  if (btn && list.contains(btn)) remove(btn);
});
```

`closest()` walks up from an inner icon or span to the button, so delegated clicks always match.

## Common mistakes

- Forgetting that `closest()` checks the element itself first.
- Checking `event.target` directly and missing clicks on an icon inside the button.

## Key points

- Event delegation uses `event.target.closest()`, so clicks on child elements still match.
- The result is checked for `null` and for staying inside the container with `contains()`.

## Interview questions

### closest vs parentElement?

`parentElement` returns only the direct parent. `closest()` keeps walking up until an element matches the selector.

### Does closest search child elements?

No. It checks only the element and its ancestors. Use `querySelector()` to search descendants.

### What does closest return if nothing matches?

It returns `null`.

## Related cards

- [.querySelector()](https://wonderium.dev/js/query-selector.md)
- [Event Bubbling](https://wonderium.dev/js/event-bubbling.md)
- [.addEventListener()](https://wonderium.dev/js/add-event-listener.md)
- [.target](https://wonderium.dev/js/event-target.md)
- [Selector](https://wonderium.dev/css/selector.md)

---

- Level: [JavaScript](https://wonderium.dev/js.md)
- HTML version: https://wonderium.dev/js/closest
- Last updated: 2026-11-25
