Help us understand the problem. What is going on with this article?

CDATA SectionはgetElementしてもCDATA

More than 1 year has passed since last update.

やったこと

埋め込んだ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);

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

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした