Selecting and Manipulating DOM Elements
Discover how to bring your web pages to life by using JavaScript to select and modify HTML elements on the fly.
Hello HTML
<h1 id="title">Hello HTML</h1>
What is the DOM?
When a browser loads a webpage, it creates a model of the page called the Document Object Model (DOM). It's a tree-like structure where every HTML tag becomes an "object" or "node." JavaScript can access this tree to read, add, change, or remove elements.
Selecting Elements
To modify an element, you must first select it. JavaScript provides powerful methods for this: getElementById()
finds an element by its unique ID, while querySelector()
finds the first element matching a CSS selector (like .my-class
or #my-id
).
Manipulating Content & Styles
Once an element is selected, you can change what's inside it. The .textContent
property changes the text, and .innerHTML
can change the full HTML content. You can also directly change its style with the .style
property, like element.style.color = 'blue'
.
Working with Attributes & Classes
Beyond content and style, you can manage HTML attributes. Use setAttribute('href', '...')
to change a link's destination, or manage CSS classes with element.classList.add('new-class')
and element.classList.remove('old-class')
to dynamically change its appearance.
Practice Zone
Interactive Test 1: Match the Methods
Drag the JavaScript methods to their correct descriptions.
Arrastra en el orden correspondiente.
Arrastra las opciones:
Completa el código:
Interactive Test 2: Complete the Code
Complete the code to select the `h1` element and change its text content.
Rellena los huecos en cada casilla.
const title = document.('h1'); title. = 'Welcome to JavaScript!';
Practice Example: Code Editor
Below is a button with the ID `action-btn`. Write JavaScript to select this button and change its text to "Clicked!".
DOM Manipulation in the Real World
DOM manipulation isn't just for changing text. It's the engine behind interactive web applications. Here are a few practical examples.
1. Form Validation
You can select an input field, check its value, and display an error message if it's invalid—all without a page refresh.
const input = document.querySelector('#email');
if (!input.value.includes('@')) {
const error = document.querySelector('.error');
error.textContent = 'Invalid email!';
}
Invalid email!
2. Creating New Elements
You can create HTML elements from scratch in JavaScript and add them to the page, perfect for building dynamic lists or notifications.
const list = document.querySelector('#items');
const newItem = document.createElement('li');
newItem.textContent = 'New Item';
list.appendChild(newItem);
- First Item
- New Item
3. Toggling UI Elements
A common use case is showing or hiding elements like a navigation menu or a modal by adding or removing a CSS class.
// .is-hidden { display: none; }
const modal = document.querySelector('#modal');
modal.classList.toggle('is-hidden');
Practical Takeaway: Learning to select, create, and modify elements is the key to transforming static documents into dynamic, responsive user interfaces.
DOM Manipulation Glossary
- DOM (Document Object Model)
- A programming interface for web documents. It represents the page so that programs can change the document structure, style, and content.
- document
- A global object that represents the entire HTML document and serves as the entry point to the page's content (the DOM).
- .getElementById('id')
- A method that returns the single element object whose `id` property matches the specified string. It's the fastest way to select an element.
- .querySelector('selector')
- Returns the first element within the document that matches the specified CSS selector (or group of selectors).
- .querySelectorAll('selector')
- Returns a static `NodeList` representing a list of the document's elements that match the specified group of selectors.
- .textContent
- A property that represents the raw text content of a node and its descendants. It's often faster and safer than `.innerHTML` for changing text.
- .innerHTML
- A property that gets or sets the HTML syntax describing the element's descendants. Use with caution as it can introduce security risks if mishandled.
- .classList
- A read-only property that returns a live `DOMTokenList` of the class attributes of the element. It has useful methods like `.add()`, `.remove()`, and `.toggle()`.