Javascript Change HTML Element Text Tutorial

In this Javascipt tutorial we learn how to return and change text, or HTML content, within an element.

We also discuss the differences between the innerText, innerHTML and textContent properties and which one we should use.

How to change an element's text content

Javascript provides us with the textContent property that we can use to change the text inside an element.

 When we change the value of the property, it will completely overwrite the previous value.
change the text content in the heading This property will only return the text inside an element. Any HTML inside the element will be stripped before the text is returned.
  span place the first paragraph's text  If we run the example above, we can see the formatting that’s present in the top paragraph is no longer there in the bottom paragraph.

This means we cannot use textContent to replace text with something that includes html.

change the text content in the heading If we run the example above, it will print the HTML code instead of creating a link.

How to change an element's innerHTML

Javascript also provides us with the innerHTML property that we can use to change the text inside an element.

change the text content in the heading Unlike the textContent property, innerHTML will return everything exactly as it is inside the element, including HTML.
  span place the first paragraph's text  This time the second paragraph has all its formatting and the link is still available because innerHTML brings any HTML along.

This means that we can include HTML elements when replacing text.

change the text content in the heading In the example above, the link is generated instead of displaying the code.

The innerText property

The innerText property works the same as the textContent property but will not return any hidden elements.

Both innerText and textContent will display content inside or tags.

Example: script
  Example: style
  The only difference is that innerText will keep the formatting, whereas textContent will not.

Which text property should you use

It depends on your situation. If you simply want to change the text in an element, any of these properties will work.

Summary: Points to remember