Apollo Creed
Apollo Creed

Reputation: 219

string from json is being written as text and not as dom elements

document.getElementById("id").innerHTML = "<div>new div</div>";

writes a new div element no problem, however a string from json:

document.getElementById("id").innerHTML = jsonData.data.children[i].data.media.oembed.html;

is always written as text with quotes!

 (ie: "<iframe></iframe"). 

yielding:

<div id="id">
   "<iframe></iframe>"
</div>   

and not

<div id="id">
   <iframe></iframe>
</div>   //as expected

I don't understand why. I want to write this string to el.innerHTML as a string without quotes so it acts like a simple element.

data from reddit.json

sample:

html: "&lt;iframe class="embedly-embed" src="//cdn.embedly.com/widgets/media.html?src=http%3A%2F%2Fwww.youtube.com%2Fembed%2FJq9JMm9h9cA%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DJq9JMm9h9cA&amp;image=http%3A%2F%2Fi.ytimg.com%2Fvi%2FJq9JMm9h9cA%2Fhqdefault.jpg&amp;key=2aa3c4d5f3de4f5b9120b660ad850dc9&amp;type=text%2Fhtml&amp;schema=youtube" width="600" height="450" scrolling="no" frameborder="0" allowfullscreen&gt;&lt;/iframe&gt;"provider_name: "YouTube"provider_url: "http://www.youtube.com/"thumbnail_height: 360thumbnail_url: "http://i.ytimg.com/vi/Jq9JMm9h9cA/hqdefault.jpg"thumbnail_width: 480title: "Good Doggy"type: "video"url: "http://www.youtube.com/watch?v=Jq9JMm9h9cA"version: "1.0"width: 600__proto__: Objecttype: "youtu.be"__proto__: Object

Upvotes: 0

Views: 233

Answers (1)

JLRishe
JLRishe

Reputation: 101710

The html property that you are accessing is XML encoded:

"html": "&lt;iframe class=\"embedly-embed\" src=\"https://cdn.emb......

Note the &lt; there at the beginning.

In order to use it as HTML, you'll need to decode it. One way you can do this is to assign it to .innerHTML, retrieve it as text, and then assign it to .innerHTML again:

var el = document.getElementById("id");
el.innerHTML = jsonData.data.children[i].data.media.oembed.html;
el.innerHTML = el.textContent;    // assign it for a second time

Obligatory warning: Make sure you darn well trust the source of the content you are using here. This opens your site wide up for an XSS attack if the source is untrustworthy.

Upvotes: 2

Related Questions