Add Content with JavaScript Summary

JavaScript can add new content to a webpage after it loads. This lets a page display another message, list item, result, or other information when it is needed.

HTML provides the starting content. JavaScript can then find an element and add more content inside it without reloading the page.

Add Text to an Element

First, give the element an ID attribute so JavaScript can find it:

<p id="message">The page is ready.</p>

This one line adds more text to the paragraph:

document.querySelector('#message').append(' New content was added.');

The paragraph now displays The page is ready. New content was added. The original words stay in place, and the new words appear after them.

How Append Works

The first part finds the paragraph:

document.querySelector('#message')

querySelector() uses the #message selector to find the element with id="message".

The append() method adds content at the end of the selected element. The text inside the quotation marks is the content it adds.

Add Instead of Replace

The Change Text lesson uses textContent to replace an element’s existing words. The append() method keeps the existing content and adds something after it.

document.querySelector('#message').textContent = 'Replacement text.';
document.querySelector('#message').append(' Added text.');

Choose between them based on the result you want. Use textContent when the old content should disappear. Use append() when it should remain.

Remove Content

JavaScript can also remove an entire HTML element. First find the element, then use remove():

document.querySelector('#extra').remove();

This removes the element with id="extra" from the page. Adding and removing content can help a page show only what someone currently needs.

When Websites Add Content

Websites often add content in response to information or actions.

  • Add a message after someone completes an action.
  • Add another item to a list.
  • Display a new search result.
  • Show more information without reloading the page.

Try Adding Your Own Text

Select Update Code in the sandbox. The JavaScript adds a second sentence to the paragraph.

Change the words inside the quotation marks and update the code again. Keep the space at the beginning so the new sentence does not run into the existing text.

Interactive Demo

The page is ready.

New content was added.

Code Sandbox

AI Tutor