Document: execCommand() method

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

Note: Although the execCommand() method is deprecated, there are still some valid use cases that do not yet have viable alternatives. For example, unlike direct DOM manipulation, modifications performed by execCommand() preserve the undo buffer (edit history). For these use cases, you can still use this method, but test to ensure cross-browser compatibility, such as by using document.queryCommandSupported().

The execCommand method implements multiple different commands. Some of them provide access to the clipboard, while others are for editing form inputs, contenteditable elements or entire documents (when switched to design mode).

To access the clipboard, the newer Clipboard API is recommended over execCommand().

Most commands affect the document's selection. For example, some commands (bold, italics, etc.) format the currently selected text, while others delete the selection, insert new elements (replacing the selection) or affect an entire line (indenting). Only the currently active editable element can be modified, but some commands (e.g., copy) can work without an editable element.

Note: Modifications performed by execCommand() may or may not trigger beforeinput and input events, depending on the browser and configuration. If triggered, the handlers for the events will run before execCommand() returns. Authors need to be careful about such recursive calls, especially if they call execCommand() in response to these events. From Firefox 82, nested execCommand() calls will always fail, see bug 1634262.

Syntax

js
execCommand(commandName, showDefaultUI, valueArgument)

Parameters

commandName

A string specifying the name of the command to execute. The following commands are specified:

backColor

Changes the document background color. In styleWithCss mode, it affects the background color of the containing block instead. This requires a <color> value string to be passed in as a value argument.

bold

Toggles bold on/off for the selection or at the insertion point.

contentReadOnly

Makes the content document either read-only or editable. This requires a boolean true/false as the value argument.

copy

Copies the current selection to the clipboard. Conditions of having this behavior enabled vary from one browser to another, and have evolved over time. Check the compatibility table to determine if you can use it in your case.