files/en-us/web/api/document/execcommand/index.md
{{ApiRef("DOM")}}{{deprecated_header}}
[!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 byexecCommand()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 {{domxref("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 {{domxref("Element/beforeinput_event", "beforeinput")}} and {{domxref("Element/input_event", "input")}} events, depending on the browser and configuration. If triggered, the handlers for the events will run beforeexecCommand()returns. Authors need to be careful about such recursive calls, especially if they callexecCommand()in response to these events. From Firefox 82, nestedexecCommand()calls will always fail, see bug 1634262.
execCommand(commandName, showDefaultUI, valueArgument)
commandName
backColor
styleWithCss mode, it affects the background color of the containing block instead. This requires a {{cssxref("<color>")}} value string to be passed in as a value argument.bold
contentReadOnly
copy
createLink
href. The URI must contain at least a single character, which may be whitespace.cut
decreaseFontSize
defaultParagraphSeparator
delete
enableAbsolutePositionEditor
enableInlineTableEditing
enableObjectResizing
fontName
"Arial") as a value argument.fontSize
1 - 7 as a value argument.foreColor
formatBlock
H1 – H6, ADDRESS, and PRE, which must be wrapped in angle brackets, such as "<H1>".)forwardDelete
heading
"H1", "H6"). (Not supported by Safari.)highlightColor
useCSS must be true for this to function.increaseFontSize
indent
insertBrOnReturn
insertHorizontalRule
insertHTML
: Inserts an {{domxref("TrustedHTML")}} instance or string of HTML markup at the insertion point (deletes selection). This requires valid HTML markup.
[!WARNING] The input is parsed as HTML and written into the DOM. APIs like this are known as injection sinks, and are potentially a vector for cross-site scripting (XSS) attacks, if the input originally came from an attacker.
You can mitigate this risk by always assigning {{domxref("TrustedHTML")}} objects instead of strings and enforcing trusted types. See the Trusted Types API for more information.
insertImage
src as a value argument. The requirements for this string are the same as createLink.insertOrderedList
insertUnorderedList
insertParagraph
insertText
italic
justifyCenter
justifyFull
justifyLeft
justifyRight
outdent
paste
: Pastes the clipboard contents at the insertion point (replaces current selection).
This feature is specified as disabled for web content, but has been implemented via the Clipboard API on some browsers. On these browsers the feature requires {{glossary("transient activation")}}, and acknowledgement of a popup UI when pasting cross-origin content. See the Browser compatibility table for more information.
redo
removeFormat
selectAll
strikeThrough
subscript
superscript
underline
undo
unlink
useCSS {{Deprecated_inline}}
[!NOTE] This argument is logically backwards (i.e., use
falseto use CSS,trueto use HTML). This has been deprecated in favor ofstyleWithCSS.
styleWithCSS
useCSS command. true modifies/generates style attributes in markup, false generates presentational elements.AutoUrlDetect
showDefaultUI
valueArgument
insertImage requires the URL of the image to insert. Specify null if no argument is needed.A boolean value that is false if the command is unsupported or disabled.
[!NOTE]
document.execCommand()only returnstrueif it is invoked as part of a user interaction. You can't use it to verify browser support before calling a command.
This example shows two very basic HTML editors, one using a {{HTMLElement("textarea")}} element and one using a {{HTMLElement("pre")}} element with the contenteditable attribute set.
Clicking the "Bold" or "Italic" buttons inserts the appropriate tags in the element, using insertText to preserve the edit history, so the user can undo the action.
<h2>textarea</h2>
<div class="actions" data-for="textarea">
<button data-el="b">Bold</button>
<button data-el="i">Italic</button>
</div>
<textarea class="editarea">Some text.</textarea>
<h2>contenteditable</h2>
<div class="actions" data-for="pre">
<button data-el="b">Bold</button>
<button data-el="i">Italic</button>
</div>
<pre contenteditable="true" class="editarea">Some text.</pre>
// Prepare action buttons
const buttonContainers = document.querySelectorAll(".actions");
for (const buttonContainer of buttonContainers) {
const buttons = buttonContainer.querySelectorAll("button");
const pasteTarget = buttonContainer.getAttribute("data-for");
for (const button of buttons) {
const elementName = button.getAttribute("data-el");
button.addEventListener("click", () =>
insertText(`<${elementName}></${elementName}>`, pasteTarget),
);
}
}
// Inserts text at cursor, or replaces selected text
function insertText(newText, selector) {
const textarea = document.querySelector(selector);
textarea.focus();
let pasted = true;
try {
if (!document.execCommand("insertText", false, newText)) {
pasted = false;
}
} catch (e) {
console.error("error caught:", e);
pasted = false;
}
if (!pasted) {
console.error("paste unsuccessful, execCommand not supported");
}
}
{{EmbedLiveSample("Using insertText", 100, 300)}}
This example has a {{HTMLElement("textarea")}} element, and a {{HTMLElement("button")}} element that you can use to paste content into it.
<button id="paste">Paste</button>
<hr />
<textarea id="text_box">Some text.</textarea>
const pasteButton = document.querySelector("#paste");
const textBox = document.querySelector("#text_box");
pasteButton.addEventListener("click", () => {
textBox.focus();
let pasted = document.execCommand("paste", false);
if (!pasted) {
textBox.textContent = "paste unsuccessful, execCommand not supported";
}
});
On browsers that implement this feature using the Clipboard API you should be able to copy same-origin content, such as text from the text area, and then paste it to replace any selected content. When you try to paste cross-origin content, such as text copied from any other page or location, you will first need to select the "Paste" UI that is displayed.
{{EmbedLiveSample("Using paste", 100, 300)}}
This feature is not part of any current specification. It is no longer on track to become a standard. There is an unofficial W3C execCommand spec draft.
{{Compat}}