- Document: execCommand() method
- Syntax
- Parameters
- Return value
- Examples
- Using insertText
- HTML
- JavaScript
- Result
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- The command line interpreter
- Entering expressions
- Accessing variables
- Autocomplete
- Defining variables
- Command history
- Working with iframes
- Helper commands
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.
When an HTML document has been switched to designMode , its document object exposes an execCommand method to run commands that manipulate the current editable region, such as form inputs or contentEditable elements.
Most commands affect the document’s selection (bold, italics, etc.), while others insert new elements (adding a link), or affect an entire line (indenting). When using contentEditable , execCommand() affects the currently active editable element.
The Clipboard API can be used instead of execCommand in many cases, but execCommand is still sometimes useful. In particular, the Clipboard API doesn’t replace the insertText command, which you can use to programmatically replace text at the cursor while preserving the undo buffer (edit history) in plain textarea and input elements.
Syntax
execCommand(aCommandName, aShowDefaultUI, aValueArgument)
Parameters
A string specifying the name of the command to execute. The following commands are specified:
Changes the document background color. In styleWithCss mode, it affects the background color of the containing block instead. This requires a value string to be passed in as a value argument.
Toggles bold on/off for the selection or at the insertion point.
Makes the content document either read-only or editable. This requires a boolean true/false as the value argument.
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.
Creates an hyperlink from the selection, but only if there is a selection. Requires a URI string as a value argument for the hyperlink’s href . The URI must contain at least a single character, which may be whitespace.
Removes the current selection and copies it to the clipboard. When this behavior is enabled varies between browsers, and its conditions have evolved over time. Check the compatibility table for usage details.
Changes the paragraph separator used when new paragraphs are created in editable text regions. See Differences in markup generation for more details.
Deletes the current selection.
Enables 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).
Enables or disables the table row/column insertion and deletion controls. The controls are disabled by default since Firefox 64 (Firefox bug 1490641).
Enables 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).
Changes the font name for the selection or at the insertion point. This requires a font name string (like «Arial» ) as a value argument.
Changes the font size for the selection or at the insertion point. This requires an integer from 1 — 7 as a value argument.
Changes a font color for the selection or at the insertion point. This requires a hexadecimal color value string as a value argument.
Adds an HTML block-level element around the line containing the current selection, replacing the block element containing the line if one exists (in Firefox, 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 tags H1 – H6 , ADDRESS , and PRE , which must be wrapped in angle brackets, such as «» .)
Deletes the character ahead of the cursor’s position, identical to hitting the Delete key on a Windows keyboard.
Adds 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.)
Changes the background color for the selection or at the insertion point. Requires a color value string as a value argument. useCSS must be true for this to function.
Indents 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.
Inserts an HTML string at the insertion point (deletes selection). Requires a valid HTML string as a value argument.
Inserts an image at the insertion point (deletes selection). Requires a URL string for the image’s src as a value argument. The requirements for this string are the same as createLink .
Creates a numbered ordered list for the selection or at the insertion point.
Creates a bulleted unordered list for the selection or at the insertion point.
Inserts a paragraph around the selection or the current line.
Inserts the given plain text at the insertion point (deletes selection).
Toggles italics on/off for the selection or at the insertion point.
Centers the selection or insertion point.
Justifies the selection or insertion point.
Justifies the selection or insertion point to the left.
Right-justifies the selection or the insertion point.
Outdents the line containing the selection or insertion point.
Pastes the clipboard contents at the insertion point (replaces current selection). Disabled for web content.
Redoes the previous undo command.
Removes all formatting from the current selection.
Selects all of the content of the editable region.
Toggles strikethrough on/off for the selection or at the insertion point.
Toggles subscript on/off for the selection or at the insertion point.
Toggles superscript on/off for the selection or at the insertion point.
Toggles underline on/off for the selection or at the insertion point.
Undoes the last executed command.
Removes the anchor element from a selected hyperlink.
Toggles 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 false to use CSS, true to use HTML). This has been deprecated in favor of styleWithCSS .
Replaces the useCSS command. true modifies/generates style attributes in markup, false generates presentational elements.
Changes the browser auto-link behavior.
A boolean value indicating whether the default user interface should be shown. This is not implemented in Mozilla.
For commands which require an input argument, is a string providing that information. For example, insertImage requires the URL of the image to insert. Specify null if no argument is needed.
Return value
A boolean value that is false if the command is unsupported or disabled.
Note: document.execCommand() only returns true if it is invoked as part of a user interaction. You can’t use it to verify browser support before calling a command. From Firefox 82, nested document.execCommand() calls will always return false .
Examples
Using insertText
This example shows two very basic HTML editors, one using a element and one using a 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.
HTML
h2>textareah2> div class="actions" data-for="textarea"> button data-el="b">Boldbutton> button data-el="i">Italicbutton> div> textarea class="editarea">Some text.textarea> h2>contenteditableh2> div class="actions" data-for="pre"> button data-el="b">Boldbutton> button data-el="i">Italicbutton> div> pre contenteditable="true" class="editarea">Some text.pre>
JavaScript
// 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"); > >
Result
Specifications
This feature is not part of any current specification. It is no longer on track to become a standard.
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Jul 17, 2023 by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.
The command line interpreter
You can interpret JavaScript expressions in real time using the command line provided by the Web Console.
Entering expressions
To enter expressions just type into the command line and press Enter . To enter multiline expressions, use Shift + Enter instead of Enter . The expression you type is echoed in the message display window, followed by the result:
From Firefox 47 onwards, if your input does not appear to be complete when you press Enter , then the Console treats this as Shift + Enter , enabling you to finish your input. For example, if you type:
and then Enter , the Console will not immediately execute the input, but will behave as if you had pressed Shift + Enter , so you can finish entering the function definition.
Accessing variables
You can access variables defined in the page, both built-in variables like window and variables added by JavaScript like jQuery :
Autocomplete
The command line has autocomplete: enter the first few letters and a popup appears with possible completions: Type Enter or Tab to accept the suggestion, use the up/down arrows to move to a different suggestion, or just keep typing if you don’t like any of the suggestions. The console suggests completions from the scope of the currently executing stack frame. This means that if you’ve hit a breakpoint in a function you get autocomplete for objects local to the function. You get autocomplete suggestions for array elements, as well:
Defining variables
You can define your own variables, and then access them:
Command history
The command line remembers commands you’ve typed: to move back and forward through your history, use the up and down arrows. From Firefox 39 onwards, this history is persisted across sessions. To clear the history, use the clearHistory() helper function.
Working with iframes
If a page contains embedded iframes, you can use the cd() command to change the console’s scope to a specific iframe, and then you can execute functions defined in the document hosted by that iframe. There are three ways to select an iframe using cd() : You can pass the iframe DOM element:
var frame = document.getElementById("frame1"); cd(frame);
var frame = document.getElementById("frame1"); cd(frame.contentWindow);
Now you’ll see that the global window’s document is the iframe: And you can call the function defined in the iframe:
Helper commands
- a selector string that will be passed to document.querySelector to locate the iframe element
- the iframe element itself
- the content window inside the iframe
copy() New in Firefox 38. Copy the argument to the clipboard. If the argument is a string, it’s copied as-is. If the argument is a DOM node, its outerHTML is copied. Otherwise, JSON.stringify will be called on the argument, and the result will be copied to the clipboard. clearHistory() New in Firefox 39. Just like a normal command line, the console command line remembers the commands you’ve typed. Use this function to clear the console’s command history.
Please refer to the Console API for more information about logging from content.