innerHTML vs innerText

This seems to be a very old topic. However I encountered a very interesting bug lately made me think about it again.

What do you think the following jQuery code will display?

myDiv2.html("A&W Restaurant");

If you are like me, a Firefox or Chrome user, you see everything as you expected. But if you use IE8, you may be surprised. IE8 and lower displays:

A&W Restaurant

Why is &W lost from myDiv1? It all comes with IE tries to be smart but not quite there yet. It tries to interpret &W or any character after & as an HTML Entity. Unfortunately, without trailing ; (semi-colon), it can’t. And even more unfortunately, it strips it off.

The fix? In my case, I shouldn’t expect the string to be HTML, so the right call should be using $.text(). However, if the string can sometimes be HTML, you know you should always HTML-encode the string before setting innerHTML. Here is a handy jQuery way to html-encode a string:

function htmlEncode(s) { return $("<div/>").text(s).html(); }

So now they display all the same on all browsers:


Even though creating a dangling div does not manipulate DOM, it still need resource from rendering engine. It will slow down your JavaScript if runs many times over.

This entry was posted in JavaScript. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s