0

When trying to store XML in variables and then render it, nothing is displayed.

Example XML string data: <?xml version="1.0" encoding="UTF-8"?>

In the script below, testvar1 is rendered, but not testvar2.

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
    <div id="target"></div>
<script>
    var testvar1 = "balls";
    var testvar2 = `<?xml version="1.0" encoding="UTF-8"?>`;
    document.getElementById("target").innerHTML = testvar1 + testvar2;
</script>
</body>
</html>

I can't think of a reason for this not to work. But I'm probably overlooking something that is obvious to everyone else...

4
  • I don't think it is related to it being defined as a template-literal. I just tested, and even if I wrap it in single-quotes it doesn't render... Commented Oct 24, 2019 at 2:55
  • @AlexanderNied If I put a simple string inside the back-ticks it works. Something like yes works. But <yes></yes> does not work. It seems all XML tags are being discarded. Commented Oct 24, 2019 at 2:59
  • Right, I'm just saying that if you write it as var testvar2 = '<?xml version="1.0" encoding="UTF-8"?>'; you get the same result; the template-literal seems unrelated to the issue. Commented Oct 24, 2019 at 3:08
  • @AlexanderNied I see your point now. I have updated the question title so that it is no longer specific to template literals. Commented Oct 24, 2019 at 4:05

2 Answers 2

1

The obvious reason is that browser interprets your XML as valid tags and tries to render elements of your XML. If you want to display pure XML to the user, use textContent property instead of innerHTML:

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
    <div id="target"></div>
<script>
    var testvar1 = "balls";
    var testvar2 = `<?xml version="1.0" encoding="UTF-8"?>`;
    document.getElementById("target").textContent = testvar1 + testvar2;
</script>
</body>
</html>
Sign up to request clarification or add additional context in comments.

1 Comment

That's a very important distinction. Really good to know this now. Thank you. This also explains why innerHTML worked on an inline SVG, but not other XML.
0

This is not a code that can be rendered because xml tag with attributes cannot be rendered by the browser.

<?xml version="1.0" encoding="UTF-8"?>

If you want render it, you must skip HTML tags like:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
  </head>
  <body>
    <div id="target"></div>
    <script>
      var testvar1 = "balls";
      var testvar2 = `&lt;?xml version="1.0" encoding="UTF-8"?&gt;`;
      document.getElementById("target").innerHTML = testvar1 + testvar2;
    </script>
  </body>
</html>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.