---
name: "up.fragment.closest"
area: "API"
kind: "JavaScript function"
parent: "up.fragment module"
url: "https://unpoly.com/api/up.fragment.closest"
---
<nav aria-label="Unpoly docs">[All docs](https://unpoly.com/index.md) · [up.fragment module](https://unpoly.com/api/up.fragment.md)</nav>

# up.fragment.closest(element, selector)

Returns the first element that matches the selector by testing the element itself and traversing up through ancestors in element's layers.

`up.fragment.closest()` will only match elements in the same [layer](https://unpoly.com/api/up.layer.md) as the given element. To match ancestors regardless of layers, use [`up.element.closest()`](https://unpoly.com/api/up.element.closest.md).

---

## Parameters {#parameters}

### element {#element}

(required)

The element on which to start the search.

Type: [Element](https://developer.mozilla.org/en-US/docs/Web/API/Element)

### selector {#selector}

(required)

The CSS selector to match.

Type: string

---

## Return value {#return-value}

element The matching element.

Returns `null` or `undefined` if no element matches in the same layer.

Type: [Element](https://developer.mozilla.org/en-US/docs/Web/API/Element) | null | undefined

