javascript

DOM Manipulation for Output

Learn how to use JavaScript to change what users see on a webpage. Discover how to update text, add new HTML elements, and display dynamic content using DOM for output.

11 min read 8 sections Tutorial
Share

The Document Object Model (DOM) is how JavaScript talks to your webpage. You will learn how to use JavaScript to change what people see on a webpage. This includes updating text, adding new parts, and showing information to your users.

DOM Manipulation for Output

DOM Manipulation for Output

Your web browser takes your HTML code and turns it into something called the Document Object Model, or DOM. Think of the DOM as a tree made of all the HTML elements on your page.

DOM manipulation means using JavaScript to change this tree. You can add new branches, change the leaves, or even remove parts. When you change the DOM, the browser automatically updates what you see on the screen.

This tutorial focuses on using DOM manipulation to output or display information to the user. You will learn how to make your webpages dynamic and interactive.

What is DOM Output?

DOM output refers to using JavaScript to display or update content on a webpage. This includes changing text, adding HTML elements, or showing dynamic data to the user.

Update Text

Change the words inside any HTML element on your page.

Add HTML

Insert new HTML tags like paragraphs or images directly into the page.

Create Elements

Build new HTML elements in JavaScript and add them to the page safely.

Dynamic Content

Show changing information, like a score or a list of items.

What is the DOM?

Getting Started

What is the DOM?

Imagine your HTML page as a family tree. Each HTML tag, like <body>, <p>, or <h1>, is a member of this family. The DOM is JavaScript's way of seeing and changing this family tree.

To change something, you first need to find it. JavaScript has special commands to find HTML elements. The most common command is document.getElementById(). It finds an element using its unique id attribute.

Once you find an element, you can change its properties. For example, you can change the text it displays.

JS · Browser
1// First, we need an HTML element to change.
2// Imagine this HTML is on your page: <p id="message">Hello there!</p>
3
4// 1. Find the HTML element using its ID.
5// We store a reference to this element in a variable called 'messageElement'.
6const messageElement = document.getElementById('message');
7
8// 2. Change the text inside that element.
9// The .textContent property lets us put new text inside the element.
10if (messageElement) {
11 messageElement.textContent = 'Welcome to the DOM!';
12}
13
14// Now, the paragraph on the webpage will show 'Welcome to the DOM!'
15
16// You can also add a new element to see the change live in the browser's console
17// This part is for demonstration and not part of the main explanation
18const newP = document.createElement('p');
19newP.id = 'message'; // Give it the ID we are looking for
20newP.textContent = 'Hello there!';
21document.body.appendChild(newP);
22
23// Rerun the script after creating the element to see the change
24setTimeout(() => {
25 const updatedMessageElement = document.getElementById('message');
26 if (updatedMessageElement) {
27 updatedMessageElement.textContent = 'Welcome to the DOM!';
28 console.log('Message updated to:', updatedMessageElement.textContent);
29 }
30}, 100); // Small delay to ensure element is appended

Script placement matters!

If your JavaScript tries to find an HTML element before that element exists on the page, it will fail. Always put your <script> tags at the end of the <body> or use defer attribute, so HTML loads first.

Changing Text and HTML Content

Changing Text and HTML Content

You can change not just text, but full HTML structures inside an element. JavaScript gives you two main ways to do this: textContent and innerHTML.

textContent only cares about the words. It is safe because it will not run any HTML code you give it. It treats everything as plain text.

innerHTML lets you put new HTML code inside an element. This is powerful but can be dangerous if you are not careful, especially with user input.

JS · Browser
1// Imagine this HTML is on your page:
2// <div id="output-area">Original content</div>
3
4// 1. Get a reference to the output area
5const outputArea = document.createElement('div'); // Create a dummy div for example
6outputArea.id = 'output-area';
7outputArea.textContent = 'Original content';
8document.body.appendChild(outputArea);
9
10const element = document.getElementById('output-area');
11
12// Using textContent:
13if (element) {
14 element.textContent = 'This is <b>plain</b> text.';
15 // The output will literally show: This is <b>plain</b> text.
16 console.log('textContent output:', element.textContent);
17}
18
19// Using innerHTML:
20// First, reset the element for a clear example
21if (element) {
22 element.textContent = 'Original content for innerHTML';
23 element.innerHTML = 'This is <b>bold</b> text.';
24 // The output will show: This is bold text.
25 // The <b> tag will actually make the text bold.
26 console.log('innerHTML output:', element.innerHTML);
27}
28
29// DANGER with innerHTML: If you put untrusted code here, it can run!
30// For example, if user input contained '<script>alert("Hacked!")</script>'
31// Always be careful when using innerHTML with data from users.
✗ BadBad: Unsafe innerHTML
const userInput = "<img src='x' onerror='alert(\'You are hacked!\')'>";
// ❌ This could run malicious code if userInput comes from an untrusted source.
document.getElementById('display').innerHTML = userInput;
✓ GoodGood: Safe textContent
const userInput = "<img src='x' onerror='alert(\'You are hacked!\')'>";
// ✅ This treats everything as plain text, preventing code from running.
document.getElementById('display').textContent = userInput;

Adding New Elements to the Page

Adding New Elements to the Page

Sometimes you don't just want to change existing content. You might want to add entirely new parts to your webpage. For example, you might add a new list item, a new image, or a new paragraph.

You can do this by creating elements in JavaScript and then adding them to the DOM tree. The main method for this is document.createElement(), which makes a new element. Then you use appendChild() to put it inside another element that is already on the page.

Using innerHTML to add elements
// HTML: <div id="container"></div>
const container = document.getElementById('container');
// If container already has content, this overwrites it all.
// It also re-parses the entire string, which can be slow.
if (container) {
container.innerHTML = '<h2>New Title</h2><p>A new paragraph.</p>';
}
VS
Using createElement and appendChild
// HTML: <div id="container"></div>
const container = document.getElementById('container');
// 1. Create the new elements in memory.
const newTitle = document.createElement('h2');
newTitle.textContent = 'New Title';
const newParagraph = document.createElement('p');
newParagraph.textContent = 'A new paragraph.';
// 2. Add them to the container.
// This adds them without affecting existing content.
if (container) {
container.appendChild(newTitle);
container.appendChild(newParagraph);
}

Prefer createElement for complex structures

When adding many new HTML elements or elements with dynamic data, createElement() and appendChild() are generally safer and more efficient. They prevent accidental code injection and allow the browser to update only the changed parts, not the entire element's content.

Building a Dynamic List

Building a Dynamic List

Let's put these ideas into practice. Imagine you have a list of items in JavaScript, like names or products. You want to display these items as a proper HTML list (<ul> with <li> tags) on your webpage.

This is a common task in web development. You will often get data from a server and need to show it to the user. Using DOM manipulation, you can build this list dynamically.

1

Prepare your HTML container

First, make sure you have an empty HTML element on your page where the list will go. Give it a unique ID.

html
1<!-- In your HTML file -->
2<ul id="my-list"></ul>
2

Get data and container

In your JavaScript, define the data you want to display. Then, get a reference to your empty list container.

javascript
1const items = ['Apple', 'Banana', 'Cherry', 'Date'];
2const listContainer = document.getElementById('my-list');
3
4// For demonstration, create the listContainer if it doesn't exist
5if (!listContainer) {
6 const ul = document.createElement('ul');
7 ul.id = 'my-list';
8 document.body.appendChild(ul);
9}
10const actualListContainer = document.getElementById('my-list');
3

Loop and create list items

Go through each item in your data. For each item, create a new <li> element. Set its textContent to the item's value.

javascript
1items.forEach(itemText => {
2 const listItem = document.createElement('li'); // Create a new <li> element
3 listItem.textContent = itemText; // Set its text content
4 actualListContainer.appendChild(listItem); // Add the <li> to the <ul>
5});
4

Verify the output

After running the script, your HTML will now have a populated <ul> list. You can inspect your browser's developer tools to see the new HTML.

javascript
1/* The HTML will look like this after the script runs:
2<ul id="my-list">
3 <li>Apple</li>
4 <li>Banana</li>
5 <li>Cherry</li>
6 <li>Date</li>
7</ul>
8*/
9console.log('List items added to:', actualListContainer.id);

Frequent DOM updates can be slow

Changing the DOM too many times, especially inside a fast loop, can make your webpage slow. Each change forces the browser to re-draw the page. For very large lists, build the entire HTML string first, then use innerHTML once, or use a DocumentFragment to add all elements at once.

Key DOM Output Methods

Key DOM Output Methods

Method/PropertyDescriptionUse CaseSecurity Note
`textContent`Gets or sets the plain text content of an element.Updating text, displaying user input safely.Safe: always treats content as plain text.
`innerHTML`Gets or sets the HTML content of an element.Injecting simple, trusted HTML snippets.Dangerous: can execute scripts if content is untrusted.
`createElement()`Creates a new HTML element in memory.Building complex elements or lists dynamically.Safe: creates an empty element, content added separately.
`appendChild()`Adds a created element as the last child of another element.Inserting new elements into the DOM tree.Safe: inserts an existing element object.

Test Your Knowledge

Test Your Knowledge

Test Your Knowledge

Quick Check

Which property should you use to change only the visible text of an HTML element, without interpreting any HTML tags?

Quick Check

You want to add a brand new <p> element to an existing <div> element on your page. Which method should you use to create the <p> element?

Quick Check

What is the main security concern when using innerHTML with data that comes from a user?

Quick Check

Which sequence of steps correctly adds a new <h2> element with the text 'New Heading' to a div with id='content'?

Quick Reference

Quick Reference

Quick Reference

Pro Tips
  • 1DOM (Document Object Model) — a tree-like representation of your HTML page that JavaScript can interact with.
  • 2DOM Manipulation — using JavaScript to change the structure, style, or content of a webpage.
  • 3Output — showing or updating information on the webpage for the user to see.
  • 4document.getElementById('id') — the most common way to find a single HTML element by its unique ID.
  • 5element.textContent — safely sets or gets the plain text inside an element. Use for untrusted input.
  • 6element.innerHTML — sets or gets the HTML content inside an element. Be careful with untrusted input due to XSS risks.
  • 7document.createElement('tagName') — creates a new HTML element in memory, like document.createElement('p').
  • 8parentElement.appendChild(childElement) — adds a created element as the last child of another element.
  • 9Script Placement — place your JavaScript <script> tags at the end of the <body> or use defer to ensure HTML elements load first.
  • 10Performance — avoid frequent, small DOM updates in loops; batch changes or use DocumentFragment for better speed.

Event Handling

Learn how to make your page interactive by responding to user clicks and keyboard inputs.

DOM Traversal

Discover how to navigate the DOM tree to find parent, sibling, and child elements.

CSS Manipulation

Control the visual styles of elements using JavaScript to change classes and inline styles.

Web Components

Explore creating reusable, encapsulated custom HTML elements for complex UIs.

You've mastered DOM Output!

You now understand how to use JavaScript to display and update content on your webpages. You can change text, add new elements, and make your web projects dynamic. This skill is fundamental for building interactive user interfaces!

Try it in the Javascript Compiler

Run and experiment with Javascript code right in your browser — no setup needed.

Continue Learning