Tutorial

Manipulating the DOM in JavaScript with innerText and innerHTML

Published on December 14, 2019
Default avatar

By joshtronic

Manipulating the DOM in JavaScript with innerText and innerHTML

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Front-end frameworks are all the rage these days. Working with a virtual DOM, while much more efficient, can be a ton of overhead when all you need to do is tweak a few elements on an existing static page. Fortunately, JavaScript comes with some methods that make it super easy to edit an element’s text as well as the HTML inside of an element.

Take that React, Angular, Vue, and whatever hot new framework I failed to mention!

Getting started

To follow along at home, all you need is a web browser and a page to manipulate.

To make it easy, we can load up any web page, open up our browser’s console and override it with our own HTML document:

document.getElementsByTagName('body')[0].innerHTML = '<div id="gator">Alligators rule!!</div>';

Once you hit enter, the existing page will be completely replaced with a light amount of HTML and a universal truth about everybody’s favorite reptile.

Editing text

All right, so in the getting started section, we sorta jumped the gun and already used innerHTML to manipulate some elements on the page.

To back it up a small bit, let’s start by changing the text of an element on a page. To do so, we’ll need to select our element and then use innerText to set the content:

document.getElementById('gator').innerText = 'OF COURSE alligators rule!';

Not much to it!

If you wanted to prepend text to an existing string of text, you can use innerText to get the current text and then prepend to it:

const currentText = document.getElementById('gator').innerText;
const nextText = 'Do alligators rule? ' + currentText;
document.getElementById('gator').innerText = nextText;

Appending text is even easier, since we can use +=:

document.getElementById('gator').innerText += ' This definitely true.';

Editing HTML

This is all well and good, but the moment we try to introduce HTML, like wrapping the string in <strong>, things fall apart.

Since innerText works with the text contents of an element, things like HTML tags end up being shown, as if the < and > were encoded as &lt; and &gt;.

No big deal though, when we want to use additional mark up with our string, all we need to do is swap out innerText for innerHTML and be on our way:

document.getElementById('gator').innerHTML = '<strong>OF COURSE</strong> alligators rule!';

And just like innerHTML we can capture the value to prepend to it, and use += to append to it:

const currentHTML = document.getElementById('gator').innerHTML;
const nextHTML = 'Do alligators rule? ' + currentHTML;
document.getElementById('gator').innerHTML = nextHTML;

document.getElementById('gator').innerHTML += ' This definitely true.';

That’s not all, when using innerHTML we can do more than just edit the text of an element. We can also use it to add additional markup, like in the case of an HTML table:

document.getElementById('gator').innerHTML = `
  <table border="1">
    <thead>
      <tr>
        <th>Reptile</th>
        <th>Awesomeness</th>
      </tr>
    </thead>
    <tbody id="tableRows">
      <tr>
        <td>Alligator</td>
        <td>9001</td>
      </tr>
    </tbody>
  </table>
`;

Subsequently, we can use innerHTML to append new rows to the table on the fly:

document.getElementById('tableRows').innerHTML += `
  <tr>
    <td>Snake</td>
    <td>-1</td>
  </tr>
`;

Conclusion

Sure, using innerText and innerHTML doesn’t come close to the power of a front-end framework that’s leveraging a virtual DOM, but hey, it gets the job done.

Fortunately, the days are long gone when innerHTML was the only option available for editing elements with JavaScript. Even though we’ve come a long way, it’s always good to know these things so you don’t go throwing an entire framework at a trivial problem.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
joshtronic

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel