Guide

    document.execCommand is deprecated. What should you use instead?

    Published 2026-11-02 · Applies to Vanilla JS and any framework that renders a contenteditable element.

    What "deprecated" means here

    document.execCommand() was added by browsers long before it was specified. The W3C editing draft that tried to describe it was never finished, and browser vendors still disagree on what many commands should produce: one browser wraps bold text in <b>, another adds a style attribute, and Enter creates a <div> in one place and a <p> in another. That is why MDN labels it deprecated and warns that it may stop working.

    At the same time, every current browser supports it, no removal has been announced, and for some tasks nothing else does the same job. So the practical question is not "how do I delete every call today" but "which calls have a better replacement now".

    Replacement by use case

    You use execCommand forUse instead
    'copy', 'cut'navigator.clipboard.writeText()
    'paste'The paste event and event.clipboardData, or navigator.clipboard.readText()
    'bold', 'italic', 'underline'beforeinput (formatBold, formatItalic…) plus Range, or an editor library
    'insertUnorderedList', 'formatBlock'Your own block model with Range, or an editor library
    'insertText', 'insertHTML'Keep execCommand for native undo, or Range plus your own history
    queryCommandState / queryCommandValueSelection, closest() and getComputedStyle() on selectionchange

    Copy and cut: the Clipboard API

    This is the one case with a clean replacement. navigator.clipboard is asynchronous, does not need a hidden textarea or a selection, and works in all current browsers. It requires a secure context (HTTPS or localhost) and should run inside a user action such as a click. Reading the clipboard with readText() may ask the user for permission; for paste inside an editor, the paste event is simpler, as shown in the paste as plain text guide.

    Copy without execCommandjs
    // Before
    textarea.select();
    document.execCommand('copy');
    
    // After: the async Clipboard API (HTTPS or localhost, inside a user gesture)
    button.addEventListener('click', async () => {
      try {
        await navigator.clipboard.writeText(textarea.value);
      } catch (err) {
        // Permission denied or an insecure context: show the text for manual copy
        console.warn('Copy failed', err);
      }
    });

    Formatting: beforeinput and the Range API

    The Input Events specification gives editors a hook before the browser changes anything. The beforeinput event fires for typing, deleting, pasting and formatting shortcuts, and its inputType says what is about to happen: formatBold, insertParagraph, deleteContentBackward, historyUndo and so on. Cancel the ones you want to control and apply your own DOM change.

    Intercept edits with beforeinputjs
    const editor = document.querySelector('#editor');
    
    editor.addEventListener('beforeinput', (event) => {
      switch (event.inputType) {
        case 'formatBold':          // Ctrl+B / Cmd+B
          event.preventDefault();
          toggleWrap('strong');
          break;
        case 'formatItalic':        // Ctrl+I / Cmd+I
          event.preventDefault();
          toggleWrap('em');
          break;
        case 'insertFromPaste':
          // Read event.dataTransfer and insert your own clean version
          break;
        // insertText, insertParagraph, deleteContentBackward...
        // are left to the browser unless your model needs them
      }
    });

    The change itself is done with the Selection and Range APIs. The example below toggles a wrapper element around a simple selection. It shows the idea, not a complete implementation: a selection that crosses paragraphs, list items or partly bold text needs splitting and merging logic, and this is the part where editor libraries spend most of their code.

    Bold without execCommandjs
    // A minimal replacement for execCommand('bold') on a simple selection.
    // Real editors also split across block boundaries, merge adjacent tags
    // and unwrap when the selection is already bold.
    function toggleWrap(tagName) {
      const sel = document.getSelection();
      if (!sel || sel.rangeCount === 0 || sel.isCollapsed) return;
    
      const range = sel.getRangeAt(0);
      const existing = closest(range.commonAncestorContainer, tagName);
    
      if (existing) {
        // Unwrap: move the children out and drop the element
        existing.replaceWith(...existing.childNodes);
        return;
      }
    
      const wrapper = document.createElement(tagName);
      wrapper.appendChild(range.extractContents());
      range.insertNode(wrapper);
    
      // Keep the formatted text selected, like execCommand does
      sel.removeAllRanges();
      const next = document.createRange();
      next.selectNodeContents(wrapper);
      sel.addRange(next);
    }
    
    function closest(node, tagName) {
      const el = node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement;
      return el?.closest(tagName);
    }

    Toolbar buttons call the same function. To keep the selection alive when the button is clicked, follow how to keep the contenteditable selection on toolbar click.

    Toolbar state: replace queryCommandState

    queryCommandState and queryCommandValue are deprecated together with execCommand, and their answers differ between browsers. Compute the state from the selection instead: take the node at the caret, look at its ancestors or its computed style, and update the toolbar on every selectionchange.

    Active state from the selectionjs
    // Before
    const isBold = document.queryCommandState('bold');
    
    // After: read the state from the selection itself
    function isBold() {
      const sel = document.getSelection();
      if (!sel || sel.rangeCount === 0) return false;
      const node = sel.getRangeAt(0).startContainer;
      const el = node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement;
      if (!el) return false;
      // Covers <b>, <strong> and CSS font-weight from your own styles
      return Number.parseInt(getComputedStyle(el).fontWeight, 10) >= 600;
    }
    
    document.addEventListener('selectionchange', () => {
      boldButton.classList.toggle('active', isBold());
    });

    When keeping execCommand is the right call

    Native undo is the main reason. The browser only adds execCommand edits to its undo stack; changes made with insertNode() or innerHTML cannot be undone with Ctrl+Z. If you drop execCommand completely, you also need your own history. Many production editors therefore still use it for text insertion and replace only the parts where browsers disagree. Keep the calls behind one wrapper so a later migration touches one file.

    Contained use of execCommandjs
    // Still the pragmatic choice for edits that must stay undoable
    // with Ctrl+Z, because only execCommand writes to the native undo stack
    document.execCommand('insertText', false, text);
    
    // Ask the browser for <p> instead of <div> on Enter
    document.execCommand('defaultParagraphSeparator', false, 'p');
    
    // Wrap every call in one place so it can be swapped out later
    function exec(command, value) {
      if (!document.queryCommandSupported?.(command)) return false;
      return document.execCommand(command, false, value);
    }

    How Scribe Editor handles it

    Scribe gives you direct methods such as editor.bold() and editor.link(url) instead of command strings. Internally it still uses execCommand for DOM mutations, which keeps native undo, and then normalizes the DOM after every command so the browser differences described above (stray spans, empty nodes, <b> versus <strong>) are cleaned up. Toolbar state comes from editor.getFormatState(), which is computed from the selection rather than queryCommandState. Your code depends on the editor API, so if the internals ever change, it does not have to. Details are in Core Concepts and the API reference.

    Scribe Editorjs
    import { Scribe } from 'scribejs-editor';
    
    const editor = Scribe.init('#editor');
    
    // Direct methods instead of command strings
    editor.bold();
    editor.link('https://scribejs.top');
    
    // State for your toolbar, without queryCommandState
    const state = editor.getFormatState();
    // → { bold: true, italic: false, link: null, ... }

    Stop writing command strings

    Scribe Editor is an MIT-licensed rich text editor under 50KB with a direct API, DOM normalization and selection-based toolbar state for React, Vue, Svelte and Vanilla JS.

    execCommand deprecation: FAQ

    Is document.execCommand deprecated?

    Yes. MDN marks document.execCommand() as deprecated and warns that it may stop working, and the editing spec that describes it was never finished. In practice every current browser still supports it, and there is no announced removal date, so existing code keeps working.

    What replaces execCommand("copy")?

    The asynchronous Clipboard API: navigator.clipboard.writeText(text) to copy and navigator.clipboard.readText() to read. It needs a secure context (HTTPS or localhost) and is usually called from a click or key handler. Reading the clipboard may show a permission prompt.

    What replaces execCommand("bold") in a rich text editor?

    There is no single browser API that does the same job. The modern approach is to listen for the beforeinput event, cancel it for inputType values such as formatBold, and apply the change yourself with the Selection and Range APIs, or to use an editor library that does this for you.

    Is queryCommandState deprecated too?

    Yes, queryCommandState, queryCommandValue and queryCommandSupported are deprecated along with execCommand, and browsers disagree on what they return. Compute toolbar state from the current selection instead: find the element at the caret and check its ancestors or its computed style on every selectionchange event.

    Does replacing execCommand break undo?

    It can. The browser only records execCommand edits in its native undo stack. Changes made directly with the Range API or by setting innerHTML are not undoable with Ctrl+Z, so an editor that drops execCommand has to keep its own history, or keep using execCommand("insertText") for text edits.