Skip to content

Instantly share code, notes, and snippets.

@rlemon
Created November 29, 2011 13:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rlemon/1404876 to your computer and use it in GitHub Desktop.
Save rlemon/1404876 to your computer and use it in GitHub Desktop.
do not use innerHTML
//when you do this:
elem.innerHTML = 'I want to set elem\'s text!';
//you're calling the browser's html parser. why so surprised? innerHTML takes an html string and turns it into DOM elements.
//you can't do that without calling an html parser.
//after the browser is done parsing your (invalid) html, it sees that it only contains text and _assumes_ you just want text and puts it into
//a text node.
//now what? it empties the element out of everything and appends the new text node. it then re-parses, re-flows and re-paints your entire page
// (since your innerHTML call can do many other things, and affect everything else in the page)
//this. is. wrong. not sparta at all. to create a text node, you're re-making your page. why don't you use the _correct_ DOM methods?
//textContent is standard. however, it doesn't work in IE
elem.textContent = 'Look mom, I\'m text!';
//innerText is an IE beast, but doesn't work in FF
elem.innerText = 'Look mom, I\'m text!';
//both of the above empty the element before adding text. I recommend the following:
var textNode = document.createTextNode( 'Look mom! I\'m a text node!' );
elem.appendChild( textNode );
//standard, works in everything, and does what you'd expect it to do. if you want to remove everything from elem, do it explicitly.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment