Selecting & Manipulating DOM Elements

Bring your static HTML to life. Learn how to use JavaScript to find, change, and create elements on your webpage dynamically.

Lesson ProgressStep 1 of 9

Hello, HTML!

0 EXP

Welcome! Let's see how JavaScript brings a static HTML page to life. This is our page.


<h1 id="title">Hello, HTML!</h1>
<button id="action-btn">Click Me</button>

What is the DOM?

When a browser loads your HTML file, it doesn't just read it as text. It creates a model of the page in memory called the Document Object Model (DOM). This model is a tree structure where every HTML tag (like <h1>, <p>, <div>) becomes an "object" or "node" in the tree.

The document object is your main entry point. Think of it as the root of the tree, giving you access to everything on the page, including the <head> and <body>.

JavaScript can access this "live" model to find, change, add, or delete elements, effectively making your webpage interactive.

System Check

What is the DOM?

Advanced Holo-Simulations

0 EXP

Log in to unlock these advanced training modules and test your skills.


Achievements

🎯
Selector Pro

Master the art of selecting DOM elements.

DOM Manipulator

Dynamically change content, styles, and classes.

🏗️
DOM Architect

Create and append new elements to the page.

Mission: Dynamic Update

On the page, there is an <h1 id="main-title"> and a <p class="content">. Use JavaScript to select the `h1` and change its text to "Welcome, Agent!".

A.D.A. Feedback:

> System integrity looks stable. Code is valid.

Challenge: Build an Element

Drag the lines of code into the correct order to create a new `div` and append it to a `ul` (list).

document.createElement('div')
const list = document.querySelector('ul')
list.appendChild(newItem)

Challenge: Manipulate a Class

Fill in the missing parts to select the element with class `card` and add the class `highlight` to it.

const card = document.('.card');card..('highlight');

Consult A.D.A.

Beyond Static Pages: The Power of DOM Manipulation

Learning to select and change elements is the "Hello, World!" of DOM manipulation. Its true power, however, is the foundation for every modern, interactive web application you use. From "liking" a post to adding an item to a shopping cart, it's all JavaScript modifying the DOM in real-time, without reloading the page.

Real-World Use Case 1: Interactive Form Validation

Instead of waiting for a user to submit a form to tell them they made a mistake, we can validate their input *as they type*.

Imagine a "password must match" field. We can "listen" for input on both fields. If the values don't match, we can select an error message <p>, change its .textContent to "Passwords do not match," and use .classList.add('error-visible') to show it. When they *do* match, we reverse the process. This provides instant, helpful feedback.

const pass1 = document.querySelector('#pass1');
const pass2 = document.querySelector('#pass2');
const errorMsg = document.querySelector('#pass-error');

function validatePassword() {
  if (pass1.value === pass2.value) {
    errorMsg.textContent = '';
    pass2.classList.remove('error-input');
  } else {
    errorMsg.textContent = 'Passwords do not match!';
    pass2.classList.add('error-input');
  }
}

pass1.addEventListener('input', validatePassword);
pass2.addEventListener('input', validatePassword);

Real-World Use Case 2: Creating a To-Do List

This is a classic example. When a user types a task into an input and clicks "Add," how does the new task appear on the list?

  1. Select the input field and the "Add" button.
  2. Select the <ul> element that holds the list.
  3. When the button is clicked:
  4. Get the .value from the input field.
  5. Use document.createElement('li') to create a new list item.
  6. Set the new list item's .textContent to the user's input value.
  7. Use listElement.appendChild(newItem) to attach the new `li` to the `ul`.
  8. Clear the input field's .value.

You've just dynamically added content to the page that didn't exist when it first loaded. The same logic applies to creating a "Delete" button inside each `li` that, when clicked, calls newItem.remove().

Security & Performance: innerHTML vs. textContent

You might be tempted to use .innerHTML to create your new list item, like: list.innerHTML += `<li>$taskText</li>`. While this *works*, it has two major problems:

  • Security Risk (XSS): If `taskText` contains a malicious script (e.g., <script>alert('hacked')</script>), .innerHTML will execute it. This is a Cross-Site Scripting (XSS) attack. .textContent is safe because it treats all content as plain text, not HTML.
  • Performance Cost: When you use `+=` on .innerHTML, the browser has to re-parse the *entire* HTML content of the `list` element, destroy all existing children, and re-create them, *plus* your new one. .appendChild() simply adds the new element at the end, which is vastly more efficient.
Key Takeaway: DOM manipulation is the API that connects your JavaScript logic to the user's visual experience. Always prefer safe, specific methods like .textContent, .createElement(), and .appendChild() over the broad, potentially dangerous .innerHTML.

JavaScript DOM Glossary

DOM (Document Object Model)
A tree-like data structure and programming interface (API) for HTML and XML documents. It represents the entire page as a collection of "nodes" and "objects" that JavaScript can interact with.
Node
The generic name for any object in the DOM tree. This includes Elements (like `<p>`), text content (Text Nodes), and comments (Comment Nodes).
Element
A specific type of Node that represents an HTML tag, such as `<h1>`, `<div>`, or `<button>`. These are the objects you'll most commonly select and manipulate.
document
A global JavaScript object that represents the entire document loaded in the browser. It's the primary entry point for all DOM queries and manipulation, e.g., document.getElementById(...).
Selector
A CSS-style string used to identify elements, such as `'#myId'`, `'.myClass'`, or `'nav > ul'`. Used by `querySelector` and `querySelectorAll`.
.getElementById(id)
The fastest method to select a *single* element by its unique `id` attribute. Returns one element or `null` if not found.
.querySelector(selector)
A highly versatile method that selects the *first* element matching a CSS selector. Returns one element or `null`.
.querySelectorAll(selector)
Selects *all* elements matching a CSS selector. Returns a static (non-live) NodeList. You can loop over this list with.forEach().
.getElementsByTagName(name)
Selects all elements with a given tag name (e.g., `'p'`). Returns a *live* HTMLCollection.
HTMLCollection vs. NodeList
Two types of lists returned by selectors. The key difference is that an HTMLCollection (from `getElementsByTagName` or `getElementsByClassName`) is *live*—it updates automatically if you _add or remove elements from the DOM. A `NodeList` (from `querySelectorAll`) is *static*—it's a snapshot in time and does not _update.
.textContent
A property to get or set the *text only* content of an element and its descendants. It ignores all HTML tags and is a safe, fast way to change text.
.innerHTML
A property to get or set the *full HTML content* of an element. It parses and renders HTML tags, but can be slow and create security vulnerabilities (XSS) if used with untrusted user input.
.setAttribute(name, value)
A method to set the value of any HTML attribute (e.g., `href`, `src`, `data-id`). E.g., img.setAttribute('src', 'new-image.png').
.style
An object property that allows you to read and set *inline* CSS styles. Property names are converted to camelCase (e.g., `font-size` becomes element.style.fontSize).
.classList
A property that provides easy methods to manage an element's classes, such as .add(className), .remove(className), and .toggle(className). This is the preferred way to change styles.
document.createElement(tagName)
Creates a new HTML element in memory (e.g.,document.createElement('div')). The element is not on _the page until you append it.
.appendChild(node)
Adds a node (usually an element) as the *last child* of a parent element. This is how you add your newly created elements to the DOM.

About the Author

Author's Avatar

TodoTutorial Team

Passionate developers and educators making programming accessible to everyone.

This article was written and reviewed by our team of senior JavaScript developers, who specialize in front-end technologies and modern web standards.

Verification and Updates

Last reviewed: November 2025.

We strive to keep our content accurate. This tutorial is based on the latest ECMAScript and DOM specifications and is periodically reviewed to reflect industry best practices.

External Resources

Found an error or have a suggestion? Contact us!