Modifying Styles & ElementsDOM

Learn to dynamically control the content and appearance of your website using the power of the Document Object Model (DOM).

Lesson ProgressStep 1 of 8

Hello, World!

0 EXP

Welcome! This is a static HTML page. Let's use JavaScript to make it interactive.


<h1 id="title">Hello, World!</h1>

Selecting Elements

Before you can change an element, you need to select it. The two most common methods are:

  • document.getElementById('unique-id'): The fastest method, but it only works if the element has an ID.
  • document.querySelector('css-selector'): The most flexible method. You can use any CSS selector (like `.my-class`, `#my-id`, or `div p`). It returns the *first* matching element.
// Selects the h1 with id="title"
const mainTitle = document.querySelector('#title');

System Check

Which method would you use to select the *first* element with a class of 'highlight'?

Advanced Holo-Simulations

0 EXP

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


Achievements

🎯
DOM Selector

Successfully select elements using various methods.

DOM Manipulator

Correctly create, add, and remove elements.

🎨
Style Maestro

Prove your mastery of dynamic styling with .classList.

Mission: Dynamic Page Update

Given the HTML `<h1 id="title">Hello</h1>`, write JavaScript to:
1. Select the `h1` and change its color to 'purple'.
2. Create a new `<p>` element with the text "Task complete!".
3. Append the new paragraph to the `document.body`.

A.D.A. Feedback:

> System integrity looks stable. Code is valid.

Challenge: Order of Operations

Drag the lines of code into the correct logical order to successfully run the script.

const p = document.createElement('p');
const h1 = document.querySelector('h1');
document.body.appendChild(p);

Challenge: Complete the Syntax

Fill in the missing methods to select the title and add the 'active' class to it.

const title = document.('#title');
title..('active');

Consult A.D.A.

Community Holo-Net

Peer Project Review

Submit your "Dynamic Page Update" project for feedback from other Net-Runners.

The Living Document: A Deep Dive into DOM Manipulation

When a browser loads a web page, it creates a model of that page's structure called the **Document Object Model (DOM)**. This model is a tree of objects, where each object represents a part of the page (like an element, an attribute, or text). **JavaScript** is the key that unlocks this model, allowing you to dynamically access and change *anything* on the page after it has loaded. This is the magic behind interactive web applications.

Part 1: Selecting Elements (The "Query")

Before you can modify an element, you must first find and select it. JavaScript provides several powerful methods for this:

  • document.getElementById('id'): The fastest and most reliable method. It selects the *one* element with a specific `id`.
  • document.querySelector('selector'): The most-flexible modern method. It uses any CSS selector (e.g., `.my-class`, `#my-id`, `div.container p`) and returns the *first* matching element.
  • document.querySelectorAll('selector'): Similar to `querySelector`, but it returns a **NodeList** (a collection) of *all* matching elements. You must then loop over this list to affect each one.
  • document.getElementsByClassName('class'): An older method that returns a **live HTMLCollection** of all elements with a given class.

Part 2: Modifying Styles

There are two primary ways to change an element's style. One is good, and one is *better*.

❌ The "Direct" Way

const title = document.querySelector('h1');
title.style.color = 'blue';
title.style.fontSize = '24px';
title.style.backgroundColor = 'yellow';

This works, but it mixes styling logic into your JavaScript, making it hard to maintain. It also adds inline styles, which are difficult to override.

✔️ The "Class" Way

/* CSS */
.title-active {
  color: blue;
  font-size: 24px;
  background-color: yellow;
}

/* JavaScript */
const title = document.querySelector('h1');
title.classList.add('title-active');

This is the best practice. Your styles live in your CSS, and your JavaScript only manages *which* styles are active. Use classList.add(), classList.remove(), and classList.toggle().

Part 3: Changing Content

When changing what an element says, you have two main choices:

  • element.textContent: This is the **safe and preferred** method. It inserts text only, and the browser does not interpret any HTML. This prevents all Cross-Site Scripting (XSS) attacks.
  • element.innerHTML: This is **powerful but dangerous**. It tells the browser to parse the string as HTML. While useful for intentionally inserting new elements, you should **never** use it with text that comes from a user (like a comment or username), as they could inject a malicious `<script>` tag.

Part 4: Creating, Adding, and Removing Elements

This is where the page truly comes alive. The flow is always: **Create**, **Configure**, **Append**.

// 1. Create the element in memory
const newDiv = document.createElement('div');

// 2. Configure it (add content, classes, etc.)
newDiv.textContent = 'I am a new element!';
newDiv.classList.add('alert');

// 3. Append it to the page to make it visible
document.body.appendChild(newDiv);

To add elements, appendChild() is the classic method. Modern JavaScript also offers append() (which can add multiple items and text) and prepend() (which adds to the beginning).

Removing an element used to be complicated. Now, it's simple:

// Just find the element and call .remove()
const elementToRemove = document.getElementById('old-news');
elementToRemove.remove();
Key Takeaway: DOM Manipulation is a three-step dance: **Select** an element, **Modify** its properties (style, content, attributes), or **Manipulate** its position (add, remove, reorder). Always prefer classList over style and textContent over innerHTML for security and maintainability.

JavaScript DOM Glossary

DOM
**Document Object Model**. A tree-like structure created by the browser that represents the entire web page. JavaScript interacts with this model, not the raw HTML file.
Node
The generic name for any single object in the DOM tree. An element is a node, text is a node, and a comment is a node.
Element
A specific type of node that represents an HTML tag, like `<h1>`, `<p>`, or `<div>`.
`document`
A global JavaScript object that represents the entire document. It's the main entry point for all DOM manipulation, e.g., `document.querySelector()`.
`querySelector()`
A method on `document` (or any element) that finds and returns the *first* element matching a CSS selector.
`querySelectorAll()`
Returns a static **NodeList** containing *all* elements that match a CSS selector.
`classList`
A property on an element that provides methods to manage its classes, such as `.add()`, `.remove()`, and `.toggle()`. The preferred way to change styles.
`style`
A property on an element that allows you to directly set *inline* CSS styles (e.g., `element.style.color = 'red'`).
`textContent`
A property to get or set the *text content* of an element. It ignores all HTML. This is the safe way to insert text.
`innerHTML`
A property to get or set the *HTML content* of an element. The browser will parse any string set here as HTML. It's powerful but carries security (XSS) risks if used with user-supplied data.
`createElement()`
A method on `document` used to create a new element in memory (e.g., `document.createElement('div')`).
`appendChild()`
A method on a parent element that adds a child element as its *last* child, making it visible on the page.
`remove()`
A method on an element that completely removes it from 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 web development experts, who have years of experience teaching JavaScript and building interactive, accessible web applications.

Verification and Updates

Last reviewed: October 2025.

We strive to keep our content accurate and up-to-date. This tutorial is based on the latest ECMAScript specifications and MDN recommendations.

External Resources

Found an error or have a suggestion? Contact us!