# Remove Element

Dismiss any content.

[![npm](https://img.shields.io/badge/npm-v4.2.0-blue)](https://www.npmjs.com/package/@preline/remove-element) [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT) [![Demo](https://img.shields.io/badge/demo-online-brightgreen)](https://preline.co/plugins/remove-element.html)

## Contents

- [Overview](#overview)
- [Installation](#installation)
- [Basic usage](#basic-usage)
- [Configuration Options](#configuration-options)
- [JavaScript API](#javascript-api)
- [Common Patterns](#common-patterns)
- [License](#license)

## Overview

The Remove Element component provides a simple way to remove or dismiss elements from the DOM with optional animation. It's commonly used for dismissible alerts, notifications, modals, or any content that should be removable.

**Key Features:**
- One-click element removal
- Optional removal animation
- Programmatic control via JavaScript API
- Simple configuration
- Event system support

## Installation

To get started, install Remove Element plugin via npm, else you can skip this step if you are already using Preline UI as a package.

```bash
npm i @preline/remove-element
```

### CSS

Use [`@source`](https://tailwindcss.com/docs/functions-and-directives#source-directive) to register the plugin's JavaScript path for Tailwind CSS scanning, then [`@import`](https://tailwindcss.com/docs/functions-and-directives#import-directive) the plugin's CSS files into your Tailwind CSS file.

```css
@import "tailwindcss";

/* @preline/remove-element */
@source "../node_modules/@preline/remove-element/*.js";
@import "./node_modules/@preline/remove-element/variants.css";
@import "./node_modules/@preline/remove-element/theme.css";
```

### JavaScript

Include the JavaScript that powers the interactive elements near the end of your `</body>` tag:

```html
<script src="./node_modules/@preline/remove-element/index.js"></script>
```

### Manual Initialization

Use the `non-auto` entry if you need manual initialization. In this mode, automatic initialization on page load is not included, so the component should be initialized explicitly.

```html
<script type="module">
  import HSRemoveElement from "@preline/remove-element/non-auto.mjs";

  new HSRemoveElement(document.querySelector("#remove-element"));
</script>
```

### Via Bundler

When using a bundler (Vite, webpack, etc.), import the plugin directly as an ES module.

`@preline/remove-element` is the auto-init entry: it scans the DOM and initializes matching elements automatically.

```js
import "@preline/remove-element";
```

`@preline/remove-element/non-auto` is the manual entry: use it when you want explicit control over when initialization happens, either via `autoInit()` or by creating a specific instance yourself.

```js
import HSRemoveElement from "@preline/remove-element/non-auto";

HSRemoveElement.autoInit();

// Or initialize a specific element manually
const el = document.querySelector("#remove-element");
if (el) new HSRemoveElement(el);
```

### TypeScript

This package ships with TypeScript type definitions. No additional `@types/` package is needed.

## Basic usage

The following example demonstrates the minimal HTML structure required for a remove element component. This is a base template without custom styling - you can apply your own CSS classes and styles as needed. Clicking the button will remove the target element.

```html
<div id="hs-dismiss-unstyled-first" class="inline-flex justify-between items-center w-full">
  <h3>
    Remove element card
  </h3>
  <button type="button" class="inline-flex justify-center items-center size-4" data-hs-remove-element="#hs-dismiss-unstyled-first">
    <span class="sr-only">Close</span>
    <svg class="shrink-0 size-4" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>
  </button>
</div>
```

**Structure Requirements:**
- `data-hs-remove-element`: Required on the trigger button, must be a valid CSS selector pointing to the element to remove
- Target element must exist in the DOM
- Button can be inside or outside the target element

**Initial State:**
- Target element is visible
- Clicking the button removes the element

## Configuration Options

### Data Options

Data options are specified via data attributes.

| Attribute | Target Element | Type | Default | Description |
| --- | --- | --- | --- | --- |
| `data-hs-remove-element` | Trigger button | string (CSS selector) | - | The element to be removed. This must be a valid CSS selector. Should be added to the button (trigger). Required. |
| `data-hs-remove-element-options` | Trigger button | object (JSON) | - | Options that can be added via the data attribute. Should be added to the button (trigger). |
| `:removeTargetAnimationClass` | Inside `data-hs-remove-element-options` | string | `"hs-removing"` | Some valid CSS class that will be applied to the target element before removal. Useful for animations. |

**Example:**
```html
<button data-hs-remove-element="#hs-alert" data-hs-remove-element-options='{
  "removeTargetAnimationClass": "fade-out"
}'>
  Close
</button>
```

## JavaScript API

The `HSRemoveElement` object is available in the global `window` object after the plugin is loaded.

### Instance Methods

These methods are called on a remove element instance.

| Method | Parameters | Return Type | Description |
| --- | --- | --- | --- |
| `destroy()` | None | `void` | Destroys the remove element instance, removes all generated markup, classes, and event listeners. Use when removing remove element from DOM. |

### Static Methods

These methods are called directly on the `HSRemoveElement` class.

| Method | Parameters | Return Type | Description |
| --- | --- | --- | --- |
| `HSRemoveElement.getInstance(target, isInstance)` | `target`: `HTMLElement \| string` (CSS selector)<br>`isInstance`: `boolean` (optional) | `HTMLElement \| { id: string \| number, element: HSRemoveElement } \| null` | Returns the remove element instance or element associated with the target. If `isInstance` is `true`, returns collection item object `{ id, element }` where `element` is the `HSRemoveElement` instance. If `isInstance` is `false` or omitted, returns the DOM element (`HTMLElement`). Returns `null` if remove element instance is not found. |

### Usage Examples

**Example 1: Destroying remove element instance**
```javascript
const instance = HSRemoveElement.getInstance('#hs-remove-element', true);

if (instance) {
  const { element } = instance;
  const destroyBtn = document.querySelector('#hs-destroy-btn');

  destroyBtn.addEventListener('click', () => {
    element.destroy();
  });
}
```

**Example 2: Getting instance and accessing properties**
```javascript
// Get the remove element instance
const instance = HSRemoveElement.getInstance('[data-hs-remove-element]', true);

if (instance) {
  const { element } = instance;

  // Access instance properties
  console.log('Target element:', element.removeTarget);
  console.log('Animation class:', element.removeTargetAnimationClass);

  // Clean up when removing from DOM
  function removeRemoveElement() {
    element.destroy();
  }
}
```

**Example 3: Destroying remove element instance**
```javascript
const instance = HSRemoveElement.getInstance('#hs-remove-element', true);

if (instance) {
  const { element } = instance;
  const removeBtn = document.querySelector('#hs-remove-btn');

  removeBtn.addEventListener('click', () => {
    // Clean up before removing from DOM
    element.destroy();
    // Now safe to remove the element
    document.querySelector('#hs-remove-element').remove();
  });
}
```

## Common Patterns

### Pattern 1: Dismissible Alert

Create a dismissible alert notification.

```html
<div id="hs-alert-first" class="alert">
  <p>This is an alert message.</p>
  <button data-hs-remove-element="#hs-alert-first">×</button>
</div>
```

### Pattern 2: With Animation

Add removal animation using CSS classes.

```html
<div id="hs-card-first" class="card">
  <h3>Card Title</h3>
  <button data-hs-remove-element="#hs-card-first" data-hs-remove-element-options='{
    "removeTargetAnimationClass": "fade-out"
  }'>
    Remove
  </button>
</div>

<style>
  .fade-out {
    opacity: 0;
    transition: opacity 0.3s;
  }
</style>
```

## License

Copyright (c) 2026 Preline Labs.

Licensed under the [MIT License](https://opensource.org/licenses/MIT).
