Modifying DOM Styles and Elements with JavaScript
Discover how to dynamically control the content and appearance of your website using the power of the Document Object Model (DOM).
Hello HTML
<body>
<h1 id="title">Hello HTML</h1>
</body>
Step 1: Selecting an Element
Before you can change anything, you need to grab the HTML element. JavaScript provides methods like document.getElementById('id')
and document.querySelector('.class')
to select specific elements from the DOM.
Step 2: Changing Styles
Once you have an element, you can change its appearance using the .style
property. For example, element.style.color = 'blue'
will change the text color. Note that CSS properties with hyphens (like `background-color`) become camelCase (backgroundColor
) in JavaScript.
Step 3: Creating and Adding Elements
You can create brand new elements from scratch using document.createElement('tag')
, like document.createElement('p')
. This creates an element in memory, but it won't appear on the page until you attach it to the DOM using a method like appendChild()
.
Step 4: Removing Elements
To remove an element, you first need to select it and then tell its parent to remove it. The common pattern is element.parentNode.removeChild(element)
. This completely removes the element and its children from the page.
Practice Zone
Interactive Test 1: Match the Action
Drag the JavaScript code to the action it performs.
Arrastra en el orden correspondiente.
Arrastra las opciones:
Completa el código:
Interactive Test 2: Complete the Code
Rellena los huecos en cada casilla.
const title = document.getElementById(''); title..fontSize = '30px';
Practice Example: Code Editor
Given the HTML, write JavaScript to change the h1
's text color to green and append a new paragraph with the text "Content added!" to the body.
Practical DOM Manipulation
Knowing *how* to change the DOM is one thing. Knowing *when* and *why* is the key to creating interactive applications.
1. Responding to User Events
Most DOM manipulation happens in response to user actions. You use event listeners to "listen" for events like clicks, mouse movements, or key presses, and then run a function to update the page.
const button = document.querySelector('button');
button.addEventListener('click', () => {
document.body.style.backgroundColor = '#e0f2fe';
});
2. Manipulating Classes for Better Styling
Instead of changing individual styles with JavaScript (e.g., `el.style.color`), it's often better to add or remove CSS classes. This keeps your styling logic in your CSS files and your behavior logic in your JavaScript. Use the element.classList
API for this.
// JS: Toggles the 'active' class on click
button.addEventListener('click', () => {
panel.classList.toggle('active');
});
/* CSS: Styles the element when active */
.panel.active {
border-color: blue;
transform: scale(1.05);
}
Pro Tip: Direct and frequent DOM manipulation can be slow. Modern frameworks like React and Vue optimize this process by using a "Virtual DOM" to batch updates efficiently.
DOM Manipulation Glossary
- document
- A global object that represents the entire HTML document. It's the entry point to all content on a page.
- .getElementById('id')
- A method of the `document` object that returns the single element with a matching `id` attribute.
- .querySelector('selector')
- Returns the *first* element within the document that matches the specified CSS selector (e.g., '.my-class', '#myId', 'p').
- .style
- A property on an element that allows you to get and set its inline CSS styles directly from JavaScript.
- .createElement('tagName')
- Creates a new HTML element specified by the tag name. The element is created in memory and is not yet part of the page.
- .appendChild(childNode)
- Adds a node (usually an element) as the last child of a specified parent node. This is how you make a created element visible.
- .removeChild(childNode)
- Removes a specified child node from its parent. The removed node is returned by the method.
- .textContent
- Gets or sets the text content of a node and its descendants. It's a safer way to change text compared to `innerHTML`.