> For the complete documentation index, see [llms.txt](https://jscula.gitbook.io/docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jscula.gitbook.io/docs/selectors/selector/chaining.md).

# Chaining

Chaining runs several actions on the same selected element in one statement.

Start with a selector. Add one method after another with a `.`.

### The basic idea

Without chaining, you select the same element for each action:

```javascript
$('#message').addClass('success');
$('#message').text('Saved');
$('#message').show();
```

With chaining, you select it once:

```javascript
$('#message')
  .addClass('success')
  .text('Saved')
  .show();
```

Both examples do the same thing. The chained version groups related changes together.

### How it works

Most methods that **change** an element return that element. This lets the next method continue from the same selection.

```javascript
$('#profile')
  .width(320)
  .height(180)
  .addClass('ready');
```

Read chained code from top to bottom:

1. Find `#profile`.
2. Set its width.
3. Set its height.
4. Add the `ready` class.

{% hint style="info" %}
Use one method per line for longer chains. It is easier to read and edit.
{% endhint %}

### Getters and setters

A **setter** changes an element. Setters can usually be chained.

```javascript
$('#title').text('Dashboard').addClass('page-title');
```

A **getter** reads a value and returns that value instead of the element. End the chain when reading a value.

```javascript
const title = $('#title').text();
```

### Event example

Use `this` inside a regular event-handler function to chain actions on the clicked element:

```javascript
$('.toast-container > div').click(function() {
  this.width('10rem').height(200);
});
```

{% hint style="info" %}
Use `function () {}` when relying on `this`. Arrow functions have different `this` behavior.
{% endhint %}
