Issue #183 (innerHTML problem, RWD/Mobile, JS Utils, Productivity)
At the top of the MDN article
for the innerHTML
property, you'll find a note that indicates what happens when you use innerHTML
to grab the content of an element that contains HTML entities like >
. This is particularly noteworthy when those entities are not escaped.
For example, let's consider the following HTML:
Notice inside the paragraph there's a greater-than symbol (>), used here to indicate a mock command prompt. There's also an ampersand character (&). Neither of these is using its HTML entity equivalent, so they're a bit risky to use in this way. However, due to HTML parsing rules, they will still appear correctly on the page.
<p>> format C & celebrate</p>
If I grab the content of the paragraph element using innerHTML
then insert it into another element using the textContent
property, this is what will appear on the page:
> format C & celebrate
This is probably not what I want. To get around this, I would want to avoid using innerHTML,
if possible. Instead, I can use textContent
, which would display the paragraph of text in the way I want it to appear, like this:
You can see the difference in this JS Bin demo
where I'm displaying the contents of the paragraph inside three output
elements. The first uses innerHTML
to grab the paragraph content and the second uses textContent
The third example uses innerHTML
to grab the paragraph content but it also uses innerHTML
instead of textContent
to display it inside the new element. This works as desired. It will depend on what you're trying to do in any particular case, but it's good to keep in mind the differences.
Of course, if there were other HTML elements inside the paragraph, then using textContent
may not be the right solution, because the HTML wouldn't be preserved. In that case, I'd probably have to grab all the nodes in the paragraph individually and only use textContent
on the text nodes.
Now on to this week's tools!