Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript and the DOM (Retiring) Making Changes to the DOM Getting and Setting Text with textContent and innerHTML

What's the difference between textContent and innerHTML?

So, in this video I don't think he explained what's the difference between them.

I searched on videos and documentation but I still don't get it, if anyone can help me telling me when to use which I will appreciate it.

Simon Coates
Simon Coates
8,377 Points

As a getter, you can see some differences demoed at https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_node_textcontent_innerhtml_innertext . As a setter, innerText and textContent seem to create text nodes (rather than HTML). Using innerHTML as a setter, you can create HTML, but there are some contexts where this is deemed to be a security risk. (This may only matter when you don't have full control over the value being used to set innerHTML.). If you use textContent, any html tags will render as text rather than be converted to HTML. (there's probably some nuance that I'm missing, but I figured it's a start)

1 Answer

With innerHTML you can change the HTML and text of the element, where as with textContext you can only change the text. For example:

element.innerHTML = "<h1>Hello</h1>;  // on the page you would see a hello that is bold
element.textContext = "<h1>Hello</h1>;  // on the page you would see <h1>Hello</h1>

Try it out in the Chrome console!

Hanane Ladj
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Hanane Ladj
Front End Web Development Techdegree Graduate 15,686 Points

@Mickael Kobela thanks for this clear and easy explanation. that really makes sense. I did try this on the console and it works. Also, Simon Coates thanks for the question!.