JavaScript Document createCDATASection() Method

Beginner
⏱️ 11 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Baseline Widely available
Instance method

What You’ll Learn

document.createCDATASection() is an instance method that creates a CDATA section node for XML documents (see MDN Document: createCDATASection()). Learn the MDN DOMParser example, why HTML pages throw NOT_SUPPORTED_ERR, the forbidden ]]> sequence, and when createTextNode() is enough — with five try-it labs.

01

Kind

Instance method

02

Arg

data string

03

Returns

CDATASection

04

XML only

not HTML

05

Avoid

]]> in data

06

Status

Baseline

Introduction

In XML, a CDATA section wraps raw text so characters like < and & are treated literally. In serialized XML it looks like:

JavaScript
<script><![CDATA[ if (a < b && c) alert("ok"); ]]></script>

MDN: createCDATASection(data) creates that kind of node in memory. You typically append it to an XML element with appendChild(), then serialize with XMLSerializer.

⚠️
HTML pages do not support CDATA (MDN)

Calling document.createCDATASection() on the live HTML page’s document throws NOT_SUPPORTED_ERR. Parse XML first with DOMParser and use the returned document.

Related tutorials: nodeType, textContent, append().

Understanding document.createCDATASection()

An instance method on a Document object — usually an XML document from DOMParser, not the HTML page document (MDN).

  • Parameterdata: string for the CDATA content (MDN).
  • Return value — a CDATASection node (MDN).
  • nodeTypeNode.CDATA_SECTION_NODE (4).
  • HTML — throws NOT_SUPPORTED_ERR (MDN).
  • Forbidden — data must not contain the literal ]]> (MDN).
  • AlternativecreateTextNode() often suffices (MDN).

📝 Syntax

General form of Document.createCDATASection (MDN):

JavaScript
createCDATASection(data)

Parameters

  • data — string containing the CDATA content (MDN).

Return value

A CDATA Section node (MDN).

MDN example (XML document)

JavaScript
const doc = new DOMParser().parseFromString("<xml></xml>", "application/xml");
const cdata = doc.createCDATASection("Some <CDATA> data & then some");
doc.querySelector("xml").appendChild(cdata);

console.log(new XMLSerializer().serializeToString(doc));
// <xml><![CDATA[Some <CDATA> data & then some]]></xml>

⚡ Quick Reference

GoalCode
Parse XML docnew DOMParser().parseFromString(xml, "application/xml")
Create CDATAdoc.createCDATASection("raw text")
Attachelement.appendChild(cdata)
Serializenew XMLSerializer().serializeToString(doc)
nodeTypeNode.CDATA_SECTION_NODE (4)
MDN statusBaseline Widely available

🔍 At a Glance

Four facts about document.createCDATASection().

Returns
CDATASection

node

Scope
XML only

MDN

Forbidden
]]>

in data

Alt
createTextNode

often

📋 When CDATA vs plain text nodes

ScenarioUse CDATAUse Text node
XML with unescaped < / &YesMust escape manually
HTML page documentNo (throws)Yes — createTextNode
User-provided raw stringOnly if no ]]>Usually safer
Serialize to XML stringCDATA wrapper in outputEscaped text in output

Examples Gallery

Examples follow MDN Document: createCDATASection(). Demos use DOMParser so they work inside HTML try-it pages.

📚 Getting Started

Create CDATA in an XML document and serialize it.

Example 1 — MDN: parse XML, create CDATA, serialize

Official MDN workflow with DOMParser and XMLSerializer.

JavaScript
const doc = new DOMParser().parseFromString("<xml></xml>", "application/xml");
const cdata = doc.createCDATASection("Some <CDATA> data & then some");
doc.querySelector("xml").appendChild(cdata);

console.log(new XMLSerializer().serializeToString(doc));
// <xml><![CDATA[Some <CDATA> data & then some]]></xml>
Try It Yourself

How It Works

Special characters stay literal inside CDATA; the serializer wraps them in <![CDATA[ ... ]]>.

Example 2 — nodeType is CDATA_SECTION_NODE (4)

Identify the node kind after creation.

JavaScript
const doc = new DOMParser().parseFromString("<root/>", "application/xml");
const cdata = doc.createCDATASection("payload");

console.log(cdata.nodeType === Node.CDATA_SECTION_NODE); // true
console.log(cdata.nodeName);  // "#cdata-section"
console.log(cdata.nodeValue); // "payload"
Try It Yourself

How It Works

CDATA sections are a distinct node type in the DOM tree, separate from Text nodes.

📈 Practical Patterns

Errors, safety rules, and alternatives.

Example 3 — HTML document throws NOT_SUPPORTED_ERR (MDN)

Do not call this on the live page’s HTML document.

JavaScript
try {
  document.createCDATASection("test"); // HTML document
} catch (err) {
  console.log(err.name); // "NotSupportedError" (NOT_SUPPORTED_ERR)
}
Try It Yourself

How It Works

MDN: HTML documents do not support CDATA sections. Use an XML document from DOMParser.

Example 4 — Forbidden ]]> in data (MDN)

The closing CDATA delimiter cannot appear inside the content string.

JavaScript
const doc = new DOMParser().parseFromString("<root/>", "application/xml");

try {
  doc.createCDATASection("bad ]]> sequence");
} catch (err) {
  console.log(err.name); // InvalidCharacterError
}
Try It Yourself

How It Works

MDN: unescaped user data is unsafe unless you validate it does not contain ]]>.

Example 5 — Alternative: createTextNode() (MDN)

When you do not need a CDATA wrapper, a text node is often enough.

JavaScript
const doc = new DOMParser().parseFromString("<msg/>", "application/xml");
const root = doc.documentElement;

// Text node — works in HTML and XML
const text = doc.createTextNode("Hello & welcome");
root.appendChild(text);

console.log(new XMLSerializer().serializeToString(doc));
// Text is escaped in XML output: Hello &amp; welcome
Try It Yourself

How It Works

MDN: createTextNode() can often replace CDATA when escaping is acceptable in serialized XML.

🚀 Common Use Cases

  • XML config / RSS feeds — embed raw markup or scripts in XML safely.
  • SVG/XML tooling — build documents programmatically with literal text.
  • Teaching DOM node types — contrast CDATA vs Text vs Comment.
  • Not for HTML SPAs — use createTextNode or textContent instead.
  • Serialization pipelines — pair with XMLSerializer (MDN example).
  • Legacy XML APIs — maintain scripts that still emit CDATA sections.

🧠 How createCDATASection() Works

1

Get an XML Document

Parse with DOMParser — not the HTML page document (MDN).

XML doc
2

Call createCDATASection(data)

Pass a string without the forbidden ]]> sequence (MDN).

Create
3

Append to an element

parent.appendChild(cdata) inserts the node in the tree.

Attach
4

Serialize or read nodeValue

Output shows <![CDATA[ ... ]]> wrapper in XML strings.

📝 Notes

  • MDN: Baseline Widely available since July 2015.
  • XML documents only — HTML throws NOT_SUPPORTED_ERR (MDN).
  • Data must not contain ]]> (MDN).
  • createTextNode() is often sufficient (MDN).
  • nodeType is 4 (CDATA_SECTION_NODE).
  • Related: nodeType, textContent, append().

Browser Support

Document.createCDATASection() is Baseline Widely available on MDN (since July 2015). Logos use the shared browser-image-sprite.png sprite from this project.

Baseline Widely available

Document.createCDATASection()

Creates CDATA Section nodes in XML documents — widely supported.

Baseline Widely available
Google Chrome Supported (XML)
Yes
Mozilla Firefox Supported (XML)
Yes
Apple Safari Supported (XML)
Yes
Microsoft Edge Supported (XML)
Yes
Opera Supported (XML)
Yes
Internet Explorer Supported (legacy XML)
Yes
createCDATASection() Wide

Bottom line: Supported in major browsers for XML documents. Not available on HTML page documents — use DOMParser first.

Conclusion

document.createCDATASection(data) creates a CDATA section node for XML documents. Use it when you need literal character data in serialized XML. On HTML page documents it throws; on XML, never pass ]]> inside data. Often, createTextNode() is the simpler choice.

Continue with createComment(), nodeType, or the JavaScript hub.

💡 Best Practices

✅ Do

  • Parse XML with DOMParser first (MDN)
  • Validate user data for ]]> before creating CDATA
  • Serialize with XMLSerializer to inspect output
  • Consider createTextNode() when escaping is fine (MDN)
  • Check nodeType === Node.CDATA_SECTION_NODE when debugging

❌ Don’t

  • Call on the live HTML document (MDN)
  • Embed raw user input without checking for ]]>
  • Expect CDATA in HTML DOM output
  • Use CDATA when a text node meets your needs
  • Confuse with HTML comments (createComment)

Key Takeaways

Knowledge Unlocked

Five things to remember about createCDATASection()

XML-only raw text nodes.

5
Core concepts
📄02

Scope

XML only

MDN
⚠️03

Ban

]]> in data

MDN
04

Alt

createTextNode

often
🛡05

Status

Baseline

2015

❓ Frequently Asked Questions

MDN: Document.createCDATASection() creates a new CDATA section node and returns it. CDATA sections hold raw text in XML where special characters like < and & do not need escaping.
No. MDN marks Document.createCDATASection() as Baseline Widely available (since July 2015). It is not Deprecated, Experimental, or Non-standard.
No (MDN). HTML documents do not support CDATA sections. Calling createCDATASection() on an HTML document throws NOT_SUPPORTED_ERR. Use it on XML documents — for example one parsed with DOMParser and application/xml.
MDN: a string parameter. The closing CDATA sequence ]]> must NOT appear inside the data — that throws NS_ERROR_DOM_INVALID_CHARACTER_ERR. Unescaped user input is unsafe unless you validate for ]]>.
MDN notes createTextNode() can often be used in its place. For HTML documents, use createTextNode() or textContent. CDATA is an XML-specific construct.
Node.CDATA_SECTION_NODE (4). You can read nodeValue or textContent for the raw character data inside the section.
Did you know?

MDN’s official example never touches the page’s HTML document — it creates a separate XML document with DOMParser, adds CDATA there, and prints the result with XMLSerializer. That pattern is the safe way to practice this API in the browser.

Next: createComment()

Learn how to create Comment nodes that work on both HTML and XML documents.

createComment() →

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