JavaScript Document queryCommandState() Method

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

What You’ll Learn

document.queryCommandState() is a deprecated, non-standard instance method that reports whether the current selection already has a given execCommand() applied (see MDN Document: queryCommandState()). Learn the true / false / null return values, MDN’s bold toolbar example, how it differs from queryCommandEnabled(), and five try-it labs.

01

Kind

Instance method

02

Args

command string

03

Returns

boolean | null

04

Reads

Selection

05

Status

Deprecated

06

Also

Non-standard

Introduction

A rich-text Bold button should look pressed when the selection is already bold, and unpressed when it is not. Legacy editors used document.queryCommandState("bold") for that.

MDN: the method tells you if the current selection has a certain Document.execCommand() command applied. Unlike queryCommandEnabled() (can I run it?), this API asks “is it already on?”

💡
Think: “Is this formatting active on the selection?”

1) Focus a contenteditable area and select text
2) Call document.queryCommandState("bold")
3) Handle true, false, or null (unknown)
4) Optionally toggle with execCommand("bold")

Related tutorials: execCommand(), queryCommandEnabled(), designMode, getSelection().

Understanding document.queryCommandState()

An instance method on the page’s document object that reads whether a named editing command is applied to the current selection (MDN).

  • command — a command from Document.execCommand() (MDN).
  • Return value — boolean, or null if the state is unknown (MDN).
  • true — the command is applied (e.g. selection is bold).
  • false — the command is not applied.
  • null — indeterminable / unknown (mixed selection or engine gap).
  • vs enabled — enabled = can run; state = already applied.

📝 Syntax

General form of Document.queryCommandState (MDN):

JavaScript
queryCommandState(command)

Parameters

  • command — a command from Document.execCommand() (MDN). Common ones for beginners: "bold", "italic", "underline".

Return value

A boolean, or null if the state is unknown (MDN).

MDN-style bold message map

JavaScript
const state = document.queryCommandState("bold");
let message;
switch (state) {
  case true:
    message = "The bold formatting will be removed from the selected text.";
    break;
  case false:
    message = "The selected text will be displayed in bold.";
    break;
  default:
    message = "The state of the 'bold' command is indeterminable.";
    break;
}
console.log(message);
document.execCommand("bold");

⚡ Quick Reference

GoalCode
Is selection bold?document.queryCommandState("bold")
Is selection italic?document.queryCommandState("italic")
Toggle after readingdocument.execCommand("bold", false, null)
Can I run bold?document.queryCommandEnabled("bold")
Feature-detecttypeof document.queryCommandState === "function"
MDN statusDeprecated & Non-standard

🔍 At a Glance

Four facts about document.queryCommandState().

Returns
bool|null

MDN

Arg
command

string

Reads
selection

formatting

Status
Deprecated

+ Non-standard

📋 State return values

ReturnMeaning (MDN + example)Typical UI
trueCommand is applied (e.g. already bold)Toolbar button looks pressed
falseCommand is not appliedButton looks idle
null / otherState unknown / indeterminableNeutral / mixed indicator

Examples Gallery

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

📚 Getting Started

MDN’s core pattern: read bold state, explain, then toggle.

Example 1 — MDN: test the state of bold

Select text in a contenteditable region, then map true / false / unknown.

JavaScript
function makeBold() {
  const state = document.queryCommandState("bold");
  let message;
  switch (state) {
    case true:
      message = "The bold formatting will be removed from the selected text.";
      break;
    case false:
      message = "The selected text will be displayed in bold.";
      break;
    default:
      message = "The state of the 'bold' command is indeterminable.";
      break;
  }
  console.log(message);
  document.execCommand("bold");
}

document.querySelector("button").addEventListener("click", makeBold);
Try It Yourself

How It Works

This matches MDN’s live example. Always select text inside contenteditable first so the command has a real selection.

Example 2 — Feature-detect the method itself

Guard against engines that remove legacy editing APIs.

JavaScript
const hasApi = typeof document.queryCommandState === "function";
console.log("queryCommandState available:", hasApi);

if (hasApi) {
  console.log("bold state:", document.queryCommandState("bold"));
} else {
  console.log("Use a modern editor library instead");
}
Try It Yourself

How It Works

Deprecated APIs can disappear. Feature-detect before calling, then prefer modern alternatives for new work.

📈 Practical Patterns

Pressed toolbar UI, multiple formatting probes, and enabled vs state.

Example 3 — Sync a pressed Bold button

Use state to toggle an aria-pressed / CSS class on the toolbar.

JavaScript
const btn = document.getElementById("boldBtn");
const editor = document.getElementById("editor");

function syncBoldButton() {
  editor.focus();
  const state =
    typeof document.queryCommandState === "function"
      ? document.queryCommandState("bold")
      : false;
  const pressed = state === true;
  btn.setAttribute("aria-pressed", String(pressed));
  btn.classList.toggle("is-pressed", pressed);
  console.log("bold pressed UI:", pressed, "(raw state:", state + ")");
}

editor.addEventListener("mouseup", syncBoldButton);
editor.addEventListener("keyup", syncBoldButton);
btn.addEventListener("click", () => {
  document.execCommand("bold", false, null);
  syncBoldButton();
});
Try It Yourself

How It Works

Re-sync on selection changes (mouseup / keyup) so the button tracks the caret as the user moves around.

Example 4 — Probe bold, italic, and underline

Report several formatting states for the current selection.

JavaScript
const names = ["bold", "italic", "underline"];
const lines = names.map((name) => {
  const state =
    typeof document.queryCommandState === "function"
      ? document.queryCommandState(name)
      : null;
  return name + ": " + String(state);
});
console.log(lines.join("\n"));
Try It Yourself

How It Works

Each command name is independent. Mixed selections may return null for some commands depending on the browser.

Example 5 — State vs enabled side by side

Compare both probes for the same formatting commands.

JavaScript
const names = ["bold", "italic", "underline"];
const lines = names.map((name) => {
  const enabled =
    typeof document.queryCommandEnabled === "function"
      ? document.queryCommandEnabled(name)
      : false;
  const state =
    typeof document.queryCommandState === "function"
      ? document.queryCommandState(name)
      : null;
  return name + " → enabled=" + enabled + ", state=" + state;
});
console.log(lines.join("\n"));
Try It Yourself

How It Works

A command can be enabled (true) while its state is still false — meaning you can apply it, but it is not applied yet. See queryCommandEnabled().

🚀 Common Use Cases

  • Legacy toolbar pressed state — highlight Bold / Italic when active (MDN UX note).
  • Explain before toggle — MDN example: tell the user whether bold will be added or removed.
  • Maintaining old editors — understand why buttons light up on selection change.
  • Interview / history knowledge — state vs enabled vs supported in the execCommand family.
  • Not a modern editor foundation — prefer dedicated libraries for new products.
  • Expect inconsistencies — MDN points to known browser bugs around this API.

🧠 How queryCommandState() Works

1

Focus an editable selection

A contenteditable region, form control, or designMode document provides the selection (MDN).

Selection
2

Pass a command name

Use a string from the execCommand set, such as "bold" (MDN).

command
3

Read boolean or null

true / false when known; null when unknown (MDN).

Return
4

Update UI or toggle

Drive pressed buttons, then optionally call execCommand. Prefer modern editors when possible.

📝 Notes

  • MDN: Deprecated and Non-standard; not part of any current specification.
  • MDN: returns a boolean or null if the state is unknown.
  • MDN: useful with rare remaining execCommand use cases for a complete toolbar UX.
  • Test cross-browser — MDN links known inconsistencies for this API.
  • Do not confuse state (applied?) with enabled (can run?) or supported (exists?).
  • Related: execCommand(), queryCommandEnabled(), designMode, getSelection().

Legacy Browser Support

Document.queryCommandState() 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.queryCommandState()

Legacy selection-state probe for editor commands — still seen with old toolbars; prefer modern editor stacks.

Legacy Not for new apps
Google Chrome Legacy editing probe still present — avoid for new apps
Legacy
Mozilla Firefox Legacy path; expect inconsistencies — 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
queryCommandState() Avoid

Bottom line: Learn it for legacy execCommand toolbars and interviews. For new rich-text UX, prefer modern editor libraries.

Conclusion

document.queryCommandState(command) reports whether a legacy editor command is applied to the current selection. It can return true, false, or null. MDN marks it deprecated and non-standard. Use it only when maintaining execCommand-based toolbars; for new apps, choose modern editors.

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

💡 Best Practices

✅ Do

  • Feature-detect typeof document.queryCommandState === "function"
  • Handle true, false, and unknown/null (MDN example)
  • Re-sync toolbar state on selection changes
  • Pair with queryCommandEnabled() when gating buttons
  • Test in every browser you still support

❌ Don’t

  • Build a new rich-text product on queryCommand* + execCommand
  • Assume every engine returns consistent mixed-selection states
  • Confuse state with enabled or supported
  • Ignore null — treat it as “unknown”
  • Forget to focus / select inside contenteditable first

Key Takeaways

Knowledge Unlocked

Five things to remember about queryCommandState()

Legacy selection-state probe — know it, rarely ship it.

5
Core concepts
⚠️02

Status

Deprecated

MDN
🛡03

Also

Non-standard

MDN
📋04

Reads

selection

formatting
📋05

Pairs with

execCommand

legacy

❓ Frequently Asked Questions

MDN: queryCommandState() tells you if the current selection has a certain Document.execCommand() command applied. For example, whether the selection is already bold.
Yes. MDN marks Document.queryCommandState() as Deprecated and Non-standard. It is not part of any current specification and is no longer on track to become a standard.
MDN: a boolean value, or null if the state is unknown (indeterminate).
MDN: if you still use deprecated execCommand() for a rare reason, queryCommandState() can help build a complete toolbar UX (pressed vs unpressed). Prefer modern editor libraries for new products.
queryCommandEnabled() asks whether a command can run right now. queryCommandState() asks whether that command’s formatting is already applied to the current selection.
MDN’s example treats a non-boolean result as indeterminable — for example a mixed selection that is partly bold and partly not, or when the browser cannot determine the state.
Did you know?

MDN’s demo reads queryCommandState("bold") before calling execCommand("bold"), so it can explain whether the next click will add or remove bold. That “preview the toggle” pattern is the classic reason legacy toolbars kept this API around.

Next: queryCommandSupported()

Learn how to check whether a legacy editor command is supported by the browser.

queryCommandSupported() →

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