1

I used ajax to download a JSON file from the internet, then set one of the keys to a variable. How do I get the contents of that variable inside a div tag? I could do:

theJsonKey = jsonObject.key;  
document.getElementById('theDivTag').innerHTML = theJsonKey;

But that doesn't seem safe since someone could put scripts or html in the JSON file.

gilly3
  • 87,962
  • 25
  • 144
  • 176
Tom
  • 269
  • 4
  • 14
  • use .innerText instead, maybe? That'll prevent the contents from being interpreted as html. Otherwise, if you're willing to use jquery, see this question: http://stackoverflow.com/questions/24816/escaping-html-strings-with-jquery – Marc B Aug 25 '11 at 17:00
  • I thought of that too, but innerText [doesn't work in FF](http://www.quirksmode.org/dom/w3c_html.html#t04) – Joseph Marikle Aug 25 '11 at 17:00

2 Answers2

2

The safest/most cross-browser way might be to do this. createTextNode innerHTML

document.getElementById('theDivTag').innerHTML = "";
document.getElementById('theDivTag').appendChild(document.createTextNode(theJsonKey));

Credit to Matt McDonald for appendChild :P

(I should have seen that one)

Joseph Marikle
  • 76,418
  • 17
  • 112
  • 129
  • 1
    If you're creating a text node, why bother with innerHTML? Just use `Node.appendChild`. innerHTML isn't exactly safe. –  Aug 25 '11 at 17:08
  • I believe this would return "[object.textnode]" instead of the actual encoded text. – Louis Ricci Aug 25 '11 at 17:12
  • @LastCoder When I was using innderHTML it did, in which case I changed it to `document.createTextNode(theJsonKey).nodeValue`, which corrected that, but appendChild is much better. See my current answer. – Joseph Marikle Aug 25 '11 at 17:15
  • This seems to work, but it keeps the previous content of the div there. Is there any way to just have the contents of `theJsonKey` in it? – Tom Aug 25 '11 at 17:19
  • @Tom at that point you can just call `document.getElementById('theDivTag').innerHTML = "";` just before appending the child. – Joseph Marikle Aug 25 '11 at 17:21
  • This is the best practice method. – Louis Ricci Aug 25 '11 at 17:23
  • 1
    A way to clean up children without innerHTML: while(element.childNodes[0]) element.removeChild(element.childNodes[0]); – James Aug 25 '11 at 17:34
  • I saw a similar solution using `.firstChild` but I thought this would be far simpler. – Joseph Marikle Aug 25 '11 at 17:40
1

What happens behind the scenes for HTML Encoding.

function safeHtml(v) {
    return v.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g, '&apos;');
}

& ==> &amp;

> ==> &gt;

< ==> &lt;

" ==> &quot;

' ==> &apos;

For a more complete list for character entities for HTML http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references

Louis Ricci
  • 20,804
  • 5
  • 48
  • 62