2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

CDATA SectionはgetElementしてもCDATA

Last updated at Posted at 2016-02-12

#やったこと
埋め込んだJavaScript(hoge_No.1)をJavaScriptで表示させようとした。
下記はその簡略化したソースコード(HTMLは最小限に省略)。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja">
<head>
<script id="SVG"><![CDATA[ hoge_No.1 ]]></script>
<script>
<![CDATA[
const SOURCE = function () {
  const Elm = document.getElementById('EMBED');
  const cdata = document.getElementById('SVG').firstChild;
  const tNode = document.createTextNode(cdata.nodeValue);
  Elm.replaceChild(tNode, Elm.firstChild);
};

(function () {
  document.addEventListener('DOMContentLoaded', SOURCE, false);
}());
]]>
</script>
<title>sample</title>
</head>
<body>
<pre id="EMBED">test</pre>
</body>
</html>

#説明
当たり前の話だが、変数cdataに格納されるのはCDATA Section。

Elm.replaceChild(cdata, Elm.firstChild);

としても表示はされるが、replaceされるのはあくまでCDATA Section(console.log()で確認済)。

そこで上記ソースにある通り下記にするとテキストノードでreplaceされる。

tNode = document.createTextNode(cdata.nodeValue);
Elm.replaceChild(tNode, Elm.firstChild);

当たり前だが認識忘れそうな話。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?