JavaScript Document clear() Method

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

What You’ll Learn

document.clear() is a deprecated instance method on the page’s Document object (see MDN Document: clear()). MDN states it does nothing and returns undefined. Learn why it still exists, what developers used to expect, and how to clear DOM content with modern APIs — with five examples and try-it labs.

01

Kind

Instance method

02

Args

None

03

Returns

undefined

04

Effect

No-op (MDN)

05

Use instead

replaceChildren

06

Status

Deprecated

Introduction

When you read legacy JavaScript tutorials or maintain old codebases, you may encounter document.clear(). The name suggests it wipes the page clean — but MDN is explicit: the method does nothing today and never raises an error.

In the early web (Netscape 4 era), developers used document.clear() together with document.write() to replace page content dynamically. Modern browsers keep the method as a silent no-op so ancient scripts do not crash.

💡
What beginners should remember

Calling document.clear() will not remove your <body> children. If you need an empty container, target the specific element and use replaceChildren().

Related tutorials: append(), removeChild(), textContent.

Understanding document.clear()

An instance method on the active document object. Defined in the HTML specification as a legacy compatibility feature (MDN).

  • Parameters — none (MDN).
  • Return valueundefined (MDN).
  • Side effect — none in modern browsers; silent no-op (MDN).
  • Errors — does not throw when called (MDN).
  • Modern replacementelement.replaceChildren() to empty a node.
  • Status — deprecated; avoid in new code (MDN).

📝 Syntax

General form of Document.clear (MDN):

JavaScript
clear()

Parameters

None (MDN).

Return value

undefined (MDN).

Modern alternatives

JavaScript
// Preferred: remove all children without parsing HTML
document.body.replaceChildren();

// Simple: assign empty HTML string (re-parses markup)
document.body.innerHTML = "";

// Loop: remove one child at a time (older pattern)
while (document.body.firstChild) {
  document.body.removeChild(document.body.firstChild);
}

// Frame / document stream (different use case — not clear())
document.open();
document.write("<h1>New content</h1>");
document.close();

⚡ Quick Reference

GoalCode
Legacy call (avoid)document.clear()
Empty bodydocument.body.replaceChildren()
Empty a divcontainer.replaceChildren()
Return valueundefined
Feature-detecttypeof document.clear === "function"
MDN statusDeprecated

🔍 At a Glance

Four facts about document.clear().

Effect
no-op

MDN

Returns
undefined

always

Errors
none

silent

Replace
replaceChildren

modern

📋 When to use each clearing approach

ScenarioRecommended APIAvoid
Empty a list container in a SPAlist.replaceChildren()document.clear()
Reset a modal bodymodalBody.replaceChildren()innerHTML if you need to preserve custom elements carefully
Strip all text from a nodenode.textContent = ""document.clear()
Legacy script maintenanceReplace call with replaceChildren()Leaving clear() expecting it to work

Examples Gallery

Examples follow MDN Document: clear() and show why the method is a no-op plus modern replacements.

📚 Getting Started

See that clear() leaves the DOM unchanged.

Example 1 — document.clear() is a no-op (MDN)

Count body children before and after calling clear().

JavaScript
const before = document.body.childElementCount;

document.clear(); // MDN: does nothing

const after = document.body.childElementCount;

console.log({ before, after, same: before === after });
// { before: N, after: N, same: true }
Try It Yourself

How It Works

MDN: the method does nothing. Your page content stays exactly as it was.

Example 2 — Return value is undefined

Capture and log what clear() returns.

JavaScript
const result = document.clear();

console.log(result);        // undefined
console.log(result === undefined); // true
Try It Yourself

How It Works

MDN lists the return value as undefined. Do not expect a boolean success flag.

📈 Practical Patterns

Modern ways to actually clear DOM content.

Example 3 — Modern: replaceChildren()

Empty a container the right way in new code.

JavaScript
const list = document.getElementById("items");

console.log("Before:", list.childElementCount); // e.g. 3

list.replaceChildren(); // removes all children

console.log("After:", list.childElementCount);  // 0
Try It Yourself

How It Works

replaceChildren() with no arguments removes every child node without assigning HTML strings.

Example 4 — Simple: innerHTML = ""

Common pattern for emptying an element (re-parses markup).

JavaScript
const panel = document.getElementById("panel");

panel.innerHTML = "<p>Loaded</p><button>Go</button>";
console.log(panel.childElementCount); // 2

panel.innerHTML = "";
console.log(panel.childElementCount); // 0
Try It Yourself

How It Works

Assigning an empty string removes children by replacing inner markup. Event listeners on removed nodes are dropped.

Example 5 — Migrate legacy document.clear() calls

Replace old code with a helper that clears a target element.

JavaScript
/** Replace deprecated document.clear() in legacy scripts */
function clearContainer(element) {
  if (element.replaceChildren) {
    element.replaceChildren();
  } else {
    element.innerHTML = "";
  }
}

// Old (deprecated — no effect):
// document.clear();

// New:
clearContainer(document.body);
Try It Yourself

How It Works

Search your codebase for document.clear() and redirect the intent to the specific element that should be emptied.

🚀 Common Use Cases

  • Reading legacy code — understand why an old script calls clear() but the page never changes.
  • Maintenance audits — find and replace deprecated calls during refactors.
  • Teaching DOM history — contrast Netscape-era patterns with modern APIs.
  • Not for SPAs — use replaceChildren() on the container you control.
  • Not for security — clearing DOM does not remove cookies, storage, or service workers.
  • Full page reset — prefer location.reload() or client-side routing, not document.clear().

🧠 How clear() Works Today

1

Script calls document.clear()

No arguments required. The call is valid on any Document instance.

Invoke
2

Browser runs legacy hook

HTML spec defines the method for web compatibility; modern engines skip visible work (MDN).

Compat
3

DOM stays unchanged

Existing nodes, styles, and event listeners remain on the page.

No-op
4

Returns undefined

No error thrown (MDN). Use replaceChildren() when you need a real clear.

📝 Notes

  • MDN: Deprecated — not recommended for new code.
  • MDN: method does nothing and does not raise an error.
  • Do not confuse with console.clear() (clears the devtools console).
  • Do not confuse with CanvasRenderingContext2D.clearRect() (clears pixels).
  • document.open() + document.write() is a different legacy document-stream pattern.
  • Related: append(), removeChild(), textContent.

Browser Support

Document.clear() is Deprecated on MDN. Logos use the shared browser-image-sprite.png sprite. The method remains callable in major engines as a compatibility no-op.

Deprecated · Legacy no-op

Document.clear()

Callable everywhere — but does nothing in modern browsers (MDN).

Legacy Compatibility only
Google Chrome No-op (deprecated)
Yes
Mozilla Firefox No-op (deprecated)
Yes
Apple Safari No-op (deprecated)
Yes
Microsoft Edge No-op (deprecated)
Yes
Opera No-op (deprecated)
Yes
Internet Explorer Legacy no-op
Partial
clear() No-op

Bottom line: Do not rely on clear() to remove DOM nodes. Use Element.replaceChildren() or innerHTML = "" on the target container instead.

Conclusion

document.clear() is a deprecated legacy method that MDN documents as a no-op: it does nothing, returns undefined, and never throws. Keep it in mind when reading old tutorials, but use element.replaceChildren() or innerHTML = "" when you need to actually empty DOM nodes.

Continue with close(), append(), or the JavaScript hub.

💡 Best Practices

✅ Do

  • Use element.replaceChildren() to remove all children
  • Target the specific container you want to empty
  • Replace legacy document.clear() during refactors
  • Feature-detect when supporting very old browsers
  • Prefer DOM APIs over document.write() for new pages

❌ Don’t

  • Expect document.clear() to wipe the page (MDN)
  • Use it in new production code
  • Confuse it with console.clear()
  • Clear document.body without considering focus and a11y
  • Assume clearing DOM removes user session data

Key Takeaways

Knowledge Unlocked

Five things to remember about clear()

Deprecated no-op — know it, don’t use it.

5
Core concepts
📝02

Returns

undefined

always
⚠️03

Status

deprecated

MDN
04

Use

replaceChildren

modern
📚05

History

Netscape era

legacy

❓ Frequently Asked Questions

MDN: Document.clear() does nothing, but does not raise any error. It is a deprecated legacy method kept for compatibility. It does not remove nodes from the page in modern browsers.
Yes. MDN marks Document.clear() as deprecated. Avoid it in new code and replace legacy calls with modern DOM APIs such as Element.replaceChildren().
undefined (MDN). It takes no parameters.
To empty an element: element.replaceChildren() (modern), element.innerHTML = '' (simple but re-parses HTML), or remove children in a loop. To replace an entire document in a frame, use document.open(), document.write(), and document.close().
Browsers keep deprecated no-op methods so very old scripts that call document.clear() do not throw ReferenceError. The HTML specification defines it as a legacy no-op for web compatibility.
Not in modern browsers — it has no visible effect (MDN). Historically it was associated with clearing document content in Netscape-era scripting, but you must use modern APIs today.
Did you know?

MDN documents document.clear() in the same family of legacy Document streaming methods as open(), write(), and close() — but unlike those, clear() today is defined to perform no action at all.

Next: close()

Learn how document.close() finishes a document stream opened with document.open().

close() →

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