CKTIS / HTML
commandfor: route a button’s command to its target
Connect one button to a specific element rather than a CSS selector or every matching node.
Version: HTML Living Standard
Syntax
<button type="button" command="--mark" commandfor="first">Mark</button>The commandfor attribute contains the ID of the element targeted by a button’s command. The target must be in the same tree. Write the ID itself, not a CSS selector with a leading hash. The commandForElement DOM property exposes the associated element where the feature is supported. A missing or unresolved target cannot receive the intended command.
The attribute selects a recipient; command supplies the operation. A custom operation produces a CommandEvent whose command and source identify the request and invoking button. Application code must implement that custom behavior. Use an explicit non-submitting button type and avoid duplicate IDs, which make the intended association unreliable.
The fixture has two possible targets but sends a custom request to only the first. Its listener marks that element and records the command name and source button; the second listener remains unused. Chromium 145 verifies the native routing. An unsupported browser reports the missing capability instead of pretending the operation happened.
Examples
<!doctype html><meta charset="utf-8">
<button id="send" type="button" command="--mark" commandfor="first">Mark</button>
<div id="first">First target</div><div id="second">Second target</div><output id="result"></output>
<script>
const send = document.querySelector('#send'); let second = false;
document.querySelector('#second').addEventListener('command', () => { second = true; });
document.querySelector('#first').addEventListener('command', event => {
event.currentTarget.dataset.marked = 'yes';
document.querySelector('#result').textContent = 'target=' + event.currentTarget.id + '; command=' + event.command + '; source=' + event.source.id + '; second=' + second;
});
if ('commandForElement' in send) send.click();
else document.querySelector('#result').textContent = 'commandfor unsupported; install an explicit event-routing fallback';
</script>Result
target=first; command=--mark; source=send; second=false
The marked target, command string, source button and untouched second target are all checked in the real browser.