Document.createCDATASection()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

createCDATASection() 创建并返回一个新的 CDATA 片段节点。

语法

var CDATASectionNode = document.createCDATASection(data);
  • CDATASectionNode 是一个 CDATA 片段节点。
  • data 包含了要被添加至 CDATA 片段的数据的字符串。

示例

js
var docu = new DOMParser().parseFromString("<xml></xml>", "application/xml");

var cdata = docu.createCDATASection("Some <CDATA> data & then some");

docu.getElementsByTagName("xml")[0].appendChild(cdata);

alert(new XMLSerializer().serializeToString(docu));
// Displays: <xml><![CDATA[Some <CDATA> data & then some]]></xml>

备注

  • This will only work with XML, not HTML documents (as HTML documents do not support CDATA sections); attempting it on an HTML document will throw NOT_SUPPORTED_ERR.
  • Will throw a NS_ERROR_DOM_INVALID_CHARACTER_ERR exception if one tries to submit the closing CDATA sequence ("]]>") as part of the data, so unescaped user-provided data cannot be safely used without with this method getting this exception (createTextNode() can often be used in its place).

规范

Specification
DOM
# ref-for-dom-document-createcomment①

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
createCDATASection

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support