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?
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.
1// First, we need an HTML element to change.2// Imagine this HTML is on your page: <p id="message">Hello there!</p>34// 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');78// 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}1314// Now, the paragraph on the webpage will show 'Welcome to the DOM!'1516// You can also add a new element to see the change live in the browser's console17// This part is for demonstration and not part of the main explanation18const newP = document.createElement('p');19newP.id = 'message'; // Give it the ID we are looking for20newP.textContent = 'Hello there!';21document.body.appendChild(newP);2223// Rerun the script after creating the element to see the change24setTimeout(() => {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.
1// Imagine this HTML is on your page:2// <div id="output-area">Original content</div>34// 1. Get a reference to the output area5const outputArea = document.createElement('div'); // Create a dummy div for example6outputArea.id = 'output-area';7outputArea.textContent = 'Original content';8document.body.appendChild(outputArea);910const element = document.getElementById('output-area');1112// 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}1819// Using innerHTML:20// First, reset the element for a clear example21if (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}2829// 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.
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;
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.
// 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>';}
// 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);}
// 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>';}
// 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.
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.
1<!-- In your HTML file -->2<ul id="my-list"></ul>
Get data and container
In your JavaScript, define the data you want to display. Then, get a reference to your empty list container.
1const items = ['Apple', 'Banana', 'Cherry', 'Date'];2const listContainer = document.getElementById('my-list');34// For demonstration, create the listContainer if it doesn't exist5if (!listContainer) {6 const ul = document.createElement('ul');7 ul.id = 'my-list';8 document.body.appendChild(ul);9}10const actualListContainer = document.getElementById('my-list');
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.
1items.forEach(itemText => {2 const listItem = document.createElement('li'); // Create a new <li> element3 listItem.textContent = itemText; // Set its text content4 actualListContainer.appendChild(listItem); // Add the <li> to the <ul>5});
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.
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/Property | Description | Use Case | Security 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
Which property should you use to change only the visible text of an HTML element, without interpreting any HTML tags?
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?
What is the main security concern when using innerHTML with data that comes from a user?
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
- 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.
- 4
document.getElementById('id')— the most common way to find a single HTML element by its unique ID. - 5
element.textContent— safely sets or gets the plain text inside an element. Use for untrusted input. - 6
element.innerHTML— sets or gets the HTML content inside an element. Be careful with untrusted input due to XSS risks. - 7
document.createElement('tagName')— creates a new HTML element in memory, likedocument.createElement('p'). - 8
parentElement.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 usedeferto ensure HTML elements load first. - 10Performance — avoid frequent, small DOM updates in loops; batch changes or use
DocumentFragmentfor 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.