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

# up.destructor(element, destructor)

Registers a function to be called when the given element is destroyed.

Elements are destroyed when they are swapped during a render pass, when their [layer](https://unpoly.com/api/up.layer.md) closes, or when [`up.destroy()`](https://unpoly.com/api/up.destroy.md) is called on the element or its container.

An alternative way to register a destructor function is to [return it from your compiler function](https://unpoly.com/learn/enhancing-elements.md#destructor).

<nav aria-label="Guides">

- [Learn: Enhancing elements with JavaScript](https://unpoly.com/learn/enhancing-elements.md#destructor)

</nav>

<nav aria-label="Contents">

#### Contents

- [Example](#example)
- [Registration time](#registration-time)
- [Reusing destructor functions](#reusing-destructor-functions)
- [Parameters](#parameters)

</nav>

## Example {#example}

The code below will log a message when `element` exits the DOM:

```js
let element = document.querySelector('.element')
up.destructor(element, () => console.log('Element was destroyed!'))
```

## Registration time {#registration-time}

The element should be attached when the destructor is registered. This is commonly done during [compilation](https://unpoly.com/learn/enhancing-elements.md).

If called on a detached element, Unpoly assumes an [async compiler](https://unpoly.com/api/up.compiler.md#async) has registered the destructor after the element has been destroyed. The destructor is then run immediately.

## Reusing destructor functions {#reusing-destructor-functions}

You may reuse the same destructor function for multiple elements. The destructor function is called with the element being destroyed:

```js
let fn = (element) => console.log('Element %o was destroyed', element)

for (let element of document.querySelectorAll('div')) {
  up.destructor(element, fn)
}
```

---

## Parameters {#parameters}

### element {#element}

(required)

The element to observe.

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

### destructor {#destructor}

(required)

One or more destructor functions.

Type: Function([Element](https://developer.mozilla.org/en-US/docs/Web/API/Element)) | [Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)<Function([Element](https://developer.mozilla.org/en-US/docs/Web/API/Element))>

