JavaScript Document execCommand() Method

Beginner
⏱️ 12 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Deprecated
Non-standard
Instance method

What You’ll Learn

document.execCommand() is a deprecated, non-standard instance method that runs editing and clipboard commands (see MDN Document: execCommand()). Learn the three parameters, common commands like bold and insertText, return-value pitfalls, undo notes, modern alternatives, and five try-it labs.

01

Kind

Instance method

02

Args

command, UI, value

03

Returns

boolean

04

Targets

selection / editable

05

Status

Deprecated

06

Also

Non-standard

Introduction

Before today’s editor libraries and Clipboard API, browsers exposed a single switchboard: document.execCommand(commandName, showDefaultUI, valueArgument). One call could bold selected text, insert HTML, or try to copy to the clipboard.

MDN: commands mainly affect the current selection inside an active editable control — a contenteditable region, a form field, or a document in designMode. Some commands (like copy) can work without an editable element.

💡
Think: legacy rich-text remote control

1) Focus an editable area and select text (if needed)
2) Call execCommand("bold", false, null) (or another command)
3) Check the boolean return value
4) Prefer Clipboard API / modern editors for new products

Related tutorials: designMode, queryCommandEnabled(), evaluate().

Understanding document.execCommand()

An instance method on the page’s document object that dispatches a named editing or clipboard command (MDN).

  • commandName — string name such as "bold", "insertText", or "copy" (MDN).
  • showDefaultUI — boolean; whether to show a default UI (not implemented in Mozilla) (MDN).
  • valueArgument — string (or null) for commands that need input, e.g. a URL for createLink (MDN).
  • Return valuefalse if unsupported or disabled; otherwise often true when run from a user gesture (MDN).
  • Undo buffer — MDN: unlike some direct DOM edits, execCommand can preserve edit history.
  • Clipboard — MDN recommends the Clipboard API over clipboard-related commands.

📝 Syntax

General form of Document.execCommand (MDN):

JavaScript
execCommand(commandName, showDefaultUI, valueArgument)

Parameters

  • commandName — string specifying the command to run (MDN). Common beginner ones: bold, italic, underline, insertText, undo, redo, copy.
  • showDefaultUI — boolean; show a default UI if the browser has one. MDN: not implemented in Mozilla. Pass false in tutorials.
  • valueArgument — extra string for commands that need data (font name, color, HTML, URL, …). Pass null when none is needed (MDN).

Return value

A boolean that is false if the command is unsupported or disabled (MDN). Important: MDN notes execCommand only returns true when invoked as part of a user interaction — you cannot rely on a cold call to prove browser support.

Beginner-friendly commands (subset of MDN list)

CommandWhat it doesValue?
bold / italic / underlineToggle formatting on the selectionNo (null)
insertTextInsert plain text (replaces selection)Yes — the text
insertHTMLInsert HTML (XSS risk — prefer Trusted Types)Yes — markup
createLinkWrap selection in a linkYes — href URI
foreColor / hiliteColorText / highlight colorYes — color string
undo / redoWalk the edit historyNo
copy / cut / pasteClipboard (legacy; prefer Clipboard API)Usually no
removeFormatStrip formatting from the selectionNo

MDN-style insertText call

JavaScript
textarea.focus();
const ok = document.execCommand("insertText", false, "");
if (!ok) {
  console.error("insertText failed or unsupported");
}

⚡ Quick Reference

GoalCode
Bold selectiondocument.execCommand("bold", false, null)
Insert textdocument.execCommand("insertText", false, "Hi")
Undodocument.execCommand("undo", false, null)
Probe a commanddocument.queryCommandSupported("bold")
Modern copyawait navigator.clipboard.writeText(text)
MDN statusDeprecated & Non-standard

🔍 At a Glance

Four facts about document.execCommand().

Returns
boolean

success-ish

Needs
user gesture

for true

Clipboard?
Clipboard API

prefer

Status
Deprecated

+ Non-standard

📋 When MDN still mentions execCommand

Prefer modern APILegacy / niche gap
ClipboardClipboard API (MDN)copy / cut / paste commands
FormattingEditor libraries / DOM + CSSOld bold / italic toolbars
Undo historyEditor-controlled historyMDN: execCommand can preserve browser undo
New productsAlways prefer standardsOnly after testing + feature checks

Examples Gallery

Examples follow MDN Document: execCommand() and practical beginner patterns. Always treat this API as legacy.

📚 Getting Started

Run a formatting command on a contenteditable region.

Example 1 — Toggle bold on a selection

Select text in the editable box, then run the bold command.

JavaScript
const editor = document.getElementById("editor");
editor.focus();

const ok = document.execCommand("bold", false, null);
console.log(ok ? "bold toggled" : "bold failed / unsupported");
Try It Yourself

How It Works

MDN: formatting commands like bold act on the current selection (or at the insertion point). Focus the editable element first so the selection is active.

Example 2 — MDN-style insertText

Insert plain text at the caret while trying to keep undo history.

JavaScript
const box = document.querySelector("textarea");
box.focus();

let pasted = true;
try {
  if (!document.execCommand("insertText", false, "Hello")) {
    pasted = false;
  }
} catch (e) {
  console.error(e);
  pasted = false;
}

console.log(pasted ? "inserted" : "insertText failed");
Try It Yourself

How It Works

MDN’s editor sample uses insertText so the change can participate in the browser undo buffer — a reason this deprecated API still appears in notes.

📈 Practical Patterns

Feature checks, undo, and modern clipboard alternatives.

Example 3 — queryCommandSupported()

MDN suggests checking support when you still rely on legacy commands.

JavaScript
const commands = ["bold", "insertText", "copy", "paste"];
const report = commands.map((name) => {
  const supported =
    typeof document.queryCommandSupported === "function"
      ? document.queryCommandSupported(name)
      : false;
  return name + ": " + (supported ? "yes" : "no");
});
console.log(report.join("\n"));
Try It Yourself

How It Works

Support is uneven — especially for clipboard commands. Combine this check with real user-gesture testing; MDN warns the execCommand return value alone is not a pre-flight probe.

Example 4 — Insert then undo

Show why undo history matters for some legacy inserts.

JavaScript
const box = document.querySelector("#note");
box.focus();
document.execCommand("insertText", false, " TEMP");
document.execCommand("undo", false, null);
console.log(box.value);
Try It Yourself

How It Works

MDN highlights undo as a reason some authors still touch execCommand. Behavior still varies — always verify in your target browsers.

Example 5 — Prefer the Clipboard API for copy

MDN recommends this path instead of execCommand("copy").

JavaScript
async function copyModern(text) {
  if (!navigator.clipboard || !navigator.clipboard.writeText) {
    console.log("Clipboard API unavailable");
    return;
  }
  await navigator.clipboard.writeText(text);
  console.log("copied with Clipboard API");
}

copyModern("Hello from CodeToFun");
Try It Yourself

How It Works

For new clipboard features, skip legacy copy / cut / paste commands and use navigator.clipboard (MDN).

🚀 Common Use Cases

  • Legacy rich-text toolbars — bold / italic / underline on contenteditable.
  • Undo-preserving inserts — MDN’s noted niche for insertText.
  • Maintaining old editors — understanding commands still shipping in production.
  • Interview / history knowledge — how browsers once exposed designMode editing.
  • Not new clipboard UX — use the Clipboard API instead (MDN).
  • Not a full modern editor — prefer dedicated libraries for new products.

🧠 How execCommand() Works

1

Focus an editable target

A contenteditable node, textarea/input, or designMode document becomes active.

Target
2

Select or place the caret

Most formatting commands act on the current selection (MDN).

Selection
3

Call execCommand

Pass the command name, usually false for UI, and a value or null.

Run
4

Read the boolean + side effects

DOM updates (and maybe input events). Prefer modern APIs when available.

📝 Notes

  • MDN: Deprecated and Non-standard; not part of any current specification.
  • MDN: Clipboard API is preferred over clipboard-related execCommand usage.
  • MDN: return true only in a user-interaction context — not a cold support probe.
  • MDN: beforeinput / input may or may not fire; nested calls can fail (e.g. Firefox).
  • MDN: insertHTML is an injection sink — treat untrusted markup as an XSS risk.
  • Related: designMode, evaluate(), parseHTML().

Legacy Browser Support

Document.execCommand() is Deprecated and Non-standard on MDN (not part of any current specification). Logos use the shared browser-image-sprite.png sprite from this project. Still present in many engines for legacy editing, but do not build new products on it.

Deprecated · Non-standard

Document.execCommand()

Legacy editing / clipboard command switchboard — still seen in old editors; prefer Clipboard API and modern editor stacks.

Legacy Not for new apps
Google Chrome Legacy editing commands still present — avoid for new apps
Legacy
Mozilla Firefox Legacy path; nested calls may fail — avoid for new apps
Legacy
Apple Safari Legacy editing support; verify each command
Legacy
Microsoft Edge Chromium legacy path — avoid for new code
Legacy
Opera Follow Chromium legacy behavior
Legacy
Internet Explorer Historic rich-text path only
Legacy
execCommand() Avoid

Bottom line: Learn it for legacy code and rare undo-preserving inserts. For clipboard and new rich-text UX, prefer modern APIs and editor libraries.

Conclusion

document.execCommand(command, false, value) was the browser’s all-in-one remote for rich-text and clipboard actions. MDN marks it deprecated and non-standard. Understand it for legacy editors and occasional undo-preserving inserts, then move clipboard work to the Clipboard API and new editors to modern stacks.

Continue with queryCommandEnabled(), exitFullscreen(), or the JavaScript hub.

💡 Best Practices

✅ Do

  • Prefer the Clipboard API for copy / paste in new apps (MDN)
  • Focus the editable target before running a command
  • Use queryCommandSupported and real browser tests when maintaining legacy UI
  • Treat insertHTML as an XSS sink — never trust raw attacker HTML (MDN)
  • Document why you still need undo-preserving insertText if you keep it

❌ Don’t

  • Build a new rich-text product on execCommand alone
  • Use the boolean return as a cold feature-detection probe (MDN)
  • Assume every command works the same in every browser
  • Nest execCommand calls inside input handlers without testing (MDN / Firefox)
  • Ignore permissions / secure-context rules for modern clipboard APIs

Key Takeaways

Knowledge Unlocked

Five things to remember about execCommand()

Legacy editing remote — know it, rarely ship it.

5
Core concepts
⚠️02

Status

Deprecated

MDN
🛡03

Also

Non-standard

MDN
📋04

Niche

undo buffer

MDN note
📋05

Clipboard

Clipboard API

prefer

❓ Frequently Asked Questions

MDN: Document.execCommand() runs editing or clipboard-related commands — for example bold/italic on a selection, insertText into contenteditable or form fields, or legacy copy/cut/paste.
Yes. MDN marks Document.execCommand() as Deprecated and Non-standard. It is not part of any current specification and is no longer on track to become a standard.
MDN notes some cases still lack full alternatives — for example modifications via execCommand can preserve the undo buffer (edit history), unlike some direct DOM edits. If you use it, test cross-browser and consider queryCommandSupported().
MDN recommends the Clipboard API (for example navigator.clipboard.writeText) over execCommand copy/cut/paste for new work.
MDN: it returns a boolean that is false if the command is unsupported or disabled. Note: true only when invoked as part of a user interaction — you cannot use the return value alone to probe support before a user gesture.
MDN: beforeinput and input may or may not fire depending on the browser. Handlers can run before execCommand returns. Nested execCommand calls can fail (e.g. Firefox 82+).
Did you know?

The old useCSS command is logically backwards on MDN (false means use CSS, true means HTML tags — and it was replaced by styleWithCSS. Tiny quirks like that are why this API is a museum piece, not a foundation.

Next: queryCommandEnabled()

Learn how to check whether a legacy editor command is currently enabled before calling execCommand().

queryCommandEnabled() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful