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 thecompatibility 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 theexecCommand() 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 usingdocument.queryCommandSupported().
TheexecCommand method implements multiple different commands. Some of them provide access to the clipboard, while others are for editingform inputs,contenteditable elements or entire documents (when switched todesign mode).
To access the clipboard, the newerClipboard API is recommended overexecCommand().
Most commands affect the document'sselection. 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 byexecCommand() may or may not triggerbeforeinput andinput 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, seebug 1634262.
In this article
Syntax
execCommand(commandName, showDefaultUI, valueArgument)Parameters
commandNameA string specifying the name of the command to execute. The following commands are specified:
backColorChanges the document background color. In
styleWithCssmode, it affects the background color of the containing block instead. This requires a<color>value string to be passed in as a value argument.boldToggles bold on/off for the selection or at the insertion point.
contentReadOnlyMakes the content document either read-only or editable. This requires a boolean true/false as the value argument.
copyCopies 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.
createLinkCreates a hyperlink from the selection, but only if there is a selection. Requires aURI string as a value argument for the hyperlink's
href. The URI must contain at least a single character, which may be whitespace.cutRemoves the current selection and copies it to the clipboard. When this behavior is enabled varies between browsers, and its conditions have evolved over time. Checkthe compatibility table for usage details.
decreaseFontSizeAdds a
<small>tag around the selection or at the insertion point.defaultParagraphSeparatorChanges the paragraph separator used when new paragraphs are created in editable text regions.
deleteDeletes the current selection.
enableAbsolutePositionEditorEnables or disables the grabber that allows absolutely-positioned elements to be moved around. The grabber is disabled by default since Firefox 64 (Firefox bug 1490641).
enableInlineTableEditingEnables or disables the table row/column insertion and deletion controls. The controls are disabled by default since Firefox 64 (Firefox bug 1490641).
enableObjectResizingEnables or disables the resize handles on images, tables, and absolutely-positioned elements and other resizable objects. The handles are disabled by default since Firefox 64 (Firefox bug 1490641).
fontNameChanges the font name for the selection or at the insertion point. This requires a font name string (like
"Arial") as a value argument.fontSizeChanges the font size for the selection or at the insertion point. This requires an integer from
1-7as a value argument.foreColorChanges a font color for the selection or at the insertion point. This requires a hexadecimal color value string as a value argument.
formatBlockAdds an HTML block-level element around the line containing the current selection, replacing the block element containing the line if one exists (in Firefox,
<blockquote>is the exception — it will wrap any containing block element). Requires a tag-name string as a value argument. Virtually all block-level elements can be used. (Legacy Edge only supports heading tagsH1–H6,ADDRESS, andPRE, which must be wrapped in angle brackets, such as"<H1>".)forwardDeleteDeletes the character ahead of thecursor's position, identical to hitting the Delete key on a Windows keyboard.
headingAdds a heading element around a selection or insertion point line. Requires the tag-name string as a value argument (i.e.,
"H1","H6"). (Not supported by Safari.)highlightColorChanges the background color for the selection or at the insertion point. Requires a color value string as a value argument.
useCSSmust betruefor this to function.increaseFontSizeAdds a
<big>tag around the selection or at the insertion point.indentIndents the line containing the selection or insertion point. In Firefox, if the selection spans multiple lines at different levels of indentation, only the least indented lines in the selection will be indented.
insertBrOnReturnControls whether the Enter key inserts a
<br>element, or splits the current block element into two.insertHorizontalRuleInserts a
<hr>element at the insertion point, or replaces the selection with it.insertHTMLInserts an HTML string at the insertion point (deletes selection). Requires a valid HTML string as a value argument.
insertImageInserts an image at the insertion point (deletes selection). Requires a URL string for the image's
srcas a value argument. The requirements for this string are the same ascreateLink.insertOrderedListCreates anumbered ordered list for the selection or at the insertion point.
insertUnorderedListCreates abulleted unordered list for the selection or at the insertion point.
insertParagraphInserts aparagraph around the selection or the current line.
insertTextInserts the given plain text at the insertion point (deletes selection).
italicToggles italics on/off for the selection or at the insertion point.
justifyCenterCenters the selection or insertion point.
justifyFullJustifies the selection or insertion point.
justifyLeftJustifies the selection or insertion point to the left.
justifyRightRight-justifies the selection or the insertion point.
outdentOutdents the line containing the selection or insertion point.
pastePastes the clipboard contents at the insertion point (replaces current selection). Disabled for web content.
redoRedoes the previous undo command.
removeFormatRemoves all formatting from the current selection.
selectAllSelects all of the content of the editable region.
strikeThroughToggles strikethrough on/off for the selection or at the insertion point.
subscriptTogglessubscript on/off for the selection or at the insertion point.
superscriptTogglessuperscript on/off for the selection or at the insertion point.
underlineTogglesunderline on/off for the selection or at the insertion point.
undoUndoes the last executed command.
unlinkRemoves theanchor element from a selected hyperlink.
useCSSDeprecatedToggles the use of HTML tags or CSS for the generated markup. Requires a boolean true/false as a value argument.
Note:This argument is logically backwards (i.e., use
falseto use CSS,trueto use HTML). This has been deprecated in favor ofstyleWithCSS.styleWithCSSReplaces the
useCSScommand.truemodifies/generatesstyleattributes in markup, false generates presentational elements.AutoUrlDetectChanges the browser auto-link behavior.
showDefaultUIA boolean value indicating whether the default user interface should be shown. This is not implemented in Mozilla.
valueArgumentFor commands which require an input argument, is a string providing that information. For example,
insertImagerequires the URL of the image to insert. Specifynullif no argument is needed.
Return value
A boolean value that isfalse if the command is unsupported or disabled.
Note:document.execCommand() only returnstrue if it is invoked as part of a user interaction. You can't use it toverify browser support before calling a command.
Examples
>Using insertText
This example shows two very basic HTML editors, one using a<textarea> element and one using a<pre> element with thecontenteditable attribute set.
Clicking the "Bold" or "Italic" buttons inserts the appropriate tags in the element, usinginsertText to preserve the edit history, so the user can undo the action.
HTML
<h2>textarea</h2><div data-for="textarea"> <button data-el="b">Bold</button> <button data-el="i">Italic</button></div><textarea>Some text.</textarea><h2>contenteditable</h2><div data-for="pre"> <button data-el="b">Bold</button> <button data-el="i">Italic</button></div><pre contenteditable="true">Some text.</pre>JavaScript
// Prepare action buttonsconst 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 textfunction 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"); }}Result
Specifications
This feature is not part of any current specification. It is no longer on track to become a standard. There is an unofficialW3C execCommand spec draft.