HOLIDAY SALE! Save 50% on Membership with code HOLIDAY50. Save 15% on Mentorship with code HOLIDAY15.

7) The Document Object Model Lesson

Change Text of DOM Elements with JavaScript

11 min to complete · By Ian Currie

Now that you know how to select an element with a method like .getElementById(), one of the most common tasks for a JavaScript developer is to manipulate the DOM. This means changing the content, style, or attributes of an element. In this lesson, you'll learn how to change the text content of an element.

Change the Text Content of DOM Elements with .textContent

The key method you'll want to use to change the text content of elements is appropriately named .textContent. For example, if you have a paragraph element with the id #paragraph, you can change its text content like this:

<button id="mainBtn">Lorem Ipsum</button>

<script>
  let btn = document.getElementById("mainBtn");
  btn.textContent = "Click Me!";
</script>

When you try out this example in the browser, you'll see that the button text is "Click Me!". When the page loads, what happens is that the browser first loads the HTML and builds the DOM. Then, it executes the JavaScript code, which changes the text content of the button.

The button is initialized with the text "Lorem Ipsum", and then the script changes it before you even have a chance to see "Lorem Ipsum".

The .innerText Property

Another way to change the text content of an element is to use the .innerText property. This property is similar in use to .textContent, but there are some differences. Take a look at this example:

<section id="container">
  <style>
    p {
      visibility: hidden;
    }
  </style>
  <h3>Lorem Ipsum</h3>
  <p>A communi observantia non est recedendum.</p>
  <p>Petierunt uti sibi concilium totius Galliae.</p>
</section>

With this HTML, you've used a bit of extra CSS to hide the paragraph elements. If you go on the JavaScript console, you can see the difference between .textContent and .innerText if you type in the following commands:

let container = document.getElementById("container");

container.textContent;
/*
    p {
      visibility: hidden;
    }
  Lorem Ipsum
  A communi observantia non est recedendum.
  Petierunt uti sibi concilium totius Galliae. 
*/

container.innerText;
/*
Lorem Ipsum
*/

As you can see, the .textContent property returns all the text content of the element, including any hidden elements and any indentation whitespace. The .innerText property, on the other hand, returns only the text content without hidden elements or the indentation.

Typically, you will only be grabbing the text from a leaf element that doesn't have a bunch of nested elements inside it. In this case, the .textContent and .innerText properties will return the same thing. But if you need to change the text content that is hidden, you'll need to use .textContent.

A difference in terms of performance however, is that .textContent is faster than .innerText. This is because .innerText has to calculate the layout of the page-it triggers a reflow-to see if the element is visible or not. This is not the case with .textContent.

Colorful illustration of a light bulb

A reflow is the process of the browser recalculating the positions and geometries of elements in the document, resulting in additional computation.

So, in general, reach for .textContent, unless you need something more specific.

The .innerHTML Property

There is yet another way to change the text content of an element. This is the .innerHTML property. Which, instead of pointing to the text content, it has the raw HTML used.

Illustration of a lighthouse

Wherever possible, you should use an alternative to this property to set the text content of an element. More information at the end of this section.

With the same HTML used in the previous section:

<section id="container">
  <style>
    p {
      visibility: hidden;
    }
  </style>
  <h3>Lorem Ipsum</h3>
  <p>A communi observantia non est recedendum.</p>
  <p>Petierunt uti sibi concilium totius Galliae.</p>
</section>

Jumping onto the console to explore it:

container.innerHTML;
/*
  <style>
    p {
      visibility: hidden;
    }
  </style>
  <h3>Lorem Ipsum</h3>
  <p>A communi observantia non est recedendum.</p>
  <p>Petierunt uti sibi concilium totius Galliae.</p>
*/

As you can see, the .innerHTML property returns the raw HTML used in the element. This is useful if you want to change the HTML of an element, not just the text content. For example, if you wanted to add a new paragraph to the container, you could do it like this:

container.innerHTML += "<p>Some new text</p>";

This would add a new paragraph to the container.

That said, you need to be careful when using .innerHTML. If you are using it to insert HTML that comes from a user, it may be used to inject malicious code into your page.

So, instead of using the .innerHTML property to set the text content of an element, prefer .textContent. If you must insert HTML, then use the .setHTML() method of the Element, which will sanitize the incoming HTML. Even then, you still need to be careful if accepting user input.

Manipulate DOM Elements From A Real Website

There is a JavaScript technique called injection. It simply means running a bit of JavaScript on a webpage that didn't originally have it. Many browser extensions rely on the ability to do this. For example, reader extensions may darken the background or make text bigger on all the webpages you visit. It does this by injecting JavaScript or CSS.

Go to this webpage and open up the Dev Tools. Now you will use the getElementsByTagName method to return all elements with the <h1> tag.

Open the console on the page and type in the following command:

document.getElementsByTagName("h1")[0].textContent = "Hello World";

Notice how the "All Questions" text has now changed!

  1. You used getElementsByTagName("h1") to return a list of the elements with that tag.
  2. Since there is only one, it returns a list of 1 element so to get that single element
  3. You need to chain a [0] on the end to get that single element.
  4. You chain a .textContent on the end of that to get the content, which is "All Questions".
  5. Then with the = sign, you assign the value of .textContent to "Hello World".

## Summary: Learn About Javascript DOM Manipulation

You've now grasped how to manipulate the DOM by changing element text, an integral part of dynamic web development. In this lesson, you've:

  • Discovered that .textContent is your go-to method for changing the text within elements
  • Found that .innerText considers the styling and will not include text from hidden elements, whereas .textContent does not
  • Identified that .innerText can cause reflows, which may affect performance, making .textContent generally the faster alternative
  • Acknowledged that when altering HTML content directly, .innerHTML is available but should be used cautiously, especially with untrusted content, to avoid security risks
  • Explored a real-world scenario of how JavaScript injection can alter website content, like changing an h1 tag to "Hello World" in a browser's developer console