HTML Declarative Commands: command and commandfor
Open and close a modal declaratively
The commandfor attribute on a button identifies another element by ID. The command attribute specifies an action, such as show-modal or close for a dialog. In supporting browsers this replaces simple click-handler scripts. Support varies, so test the feature and provide another route to the action if needed.
<button type="button" commandfor="rules" command="show-modal">Read rules</button><dialog id="rules" aria-labelledby="rule-title"> <h2 id="rule-title">Rules</h2> <p>Keep examples short.</p> <button type="button" commandfor="rules" command="close">Done</button></dialog>Read rules opens a modal; Done closes it in a supporting browser.
Control a popover
Commands also include show-popover, hide-popover and toggle-popover for popover targets. Choose an action that matches the target. For simple popovers the earlier popovertarget attribute is another native approach.
<button type="button" commandfor="hint" command="toggle-popover">Toggle hint</button><p id="hint" popover>Review the examples.</p>The button toggles the popover in supporting browsers.
Handle a custom command
Custom command names begin with two hyphens. They dispatch a command event to the target rather than implementing an action automatically. The listener below reads event.command and updates the target text. This is a small JavaScript enhancement; the command is not a function name.
<button type="button" commandfor="message" command="--clear">Clear note</button><p id="message">Draft note</p><script> const message = document.getElementById("message"); message.addEventListener("command", event => { if (event.command === "--clear") message.textContent = "Cleared"; });</script>Clear note changes the paragraph to Cleared when custom commands are supported.
Common mistakes and practice
Use unique IDs, a compatible target, and type="button" for non-submitting actions. A property check such as "command" in HTMLButtonElement.prototype can help detect the API, but test the actual required action too. Do not wire both a native command and an unconditional fallback listener to the same button.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
HTML Declarative Commands: command and commandfor — Knowledge Check
Apply the interaction concepts taught in this lesson.
What does commandfor identify?
Which command opens a modal dialog?
Which command toggles a popover?
How does a custom command name begin?
What is needed for a custom command action?