What is CDATA?
May 18, 2021 · 2 min. read
TLDR;
- CDATA is only applicable to XML and XHTML.
- If you are writing HTML don't use CDATA, as browsers will ignore it when parsing HTML.
Meaning
CDATA means character data. Text wrapped with CDATA tags is intended to be interpreted as character data, not as markup. It is commonly used in XML to tell the parser "Hey, this is literal text, not markup!"
For example, if you wrote <breakfast>Oatmeal</breakfast>
, an XML parser would interpret <breakfast>
as an opening tag and </breakfast>
as a closing tag. The result be an object with the text content "Oatmeal". CDATA changes this behavior. It tells the parser to ignore any tags and just treat the enclosed text as literal text.
Syntax
Starting tag:
<![CDATA[
Ending tag:
]]>
Complete example:
<![CDATA[<fruit>Apple</fruit>]]>
When To Use
You can use CDATA when you are writing XML. If you are writing HTML (not XHTML), don't use it. HTML parsers don't recognize CDATA and will ignore it. There was a time when XHMTL was a thing, so CDATA mattered. That time has passed. Here's an example of what happens when you try to use CDATA with HTML:
<![CDATA[
Not exactly what you want, right?
What About Special Characters in Javascript?
Again, this only matters if you are writing XHTML. In XHMTL this would be a problem:
<script>
console.log('<fruit>Apple</fruit>');
console.log(3 < 9);
</script>
The parser would interpret <fruit>Apple</fruit>
as a DOM element and may get confused by the <
in 3 < 9
. Modern browsers interpreting pages with the document type of HTML don't have a problem with this. For proof, take a glance at the source for this page and the JS console. I've included the script above on this page. You'll see that the browser correctly interprets the JS without a problem.