# \[commandfor\]

> The `commandfor` HTML attribute links a button to the element it controls through invoker commands.

## What does commandfor do on an HTML button?

The attribute of the `<button>` element that references the `id` of the element to be controlled. Used together with the `command` attribute to declaratively open dialogs, toggle popovers or send custom commands to elements without writing event handlers.

- Topic: Element Attributes
- Type: attribute
- Browser support: Chrome 135+, Chrome Android 135+, Edge 135+, Firefox 144+, Firefox Android 144+, Safari 26.2+, Safari iOS 26.2+

## Example

Wrong:

```html
<button commandfor="#menu" command="toggle-popover">Menu</button>
<div id="menu" popover>...</div>
```

Right:

```html
<button commandfor="menu" command="toggle-popover">Menu</button>
<div id="menu" popover>...</div>
```

`commandfor` takes a plain id, not a CSS selector.

## Common mistakes

- Putting the target inside a different shadow root, so the `id` is not found.

## Key points

- The value is the plain `id` of the target, without a '#'.
- The target element exists in the same document or shadow root as the button.
- The attribute is on a `<button>`, not on a `<div>` or a link.
- The button also has a `command` attribute that names the action.

## Interview questions

### Which commands work with commandfor?

Built-in ones include 'show-modal', 'close', 'request-close', 'show-popover', 'hide-popover' and 'toggle-popover'.

### Can commandfor run my own JavaScript?

Yes. Use a custom command that starts with '--' and listen for the `command` event on the target.

## Related cards

- [\[command\]](https://wonderium.dev/html/command-attribute.md)
- [\[popovertarget\]](https://wonderium.dev/html/popovertarget.md)
- [`<dialog>`](https://wonderium.dev/html/dialog.md)
- [`<button>`](https://wonderium.dev/html/button.md)
- [\[id\]](https://wonderium.dev/html/id.md)

---

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