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

Welcome! Let's see how JavaScript can bring a static HTML page to life by manipulating it directly.

<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:

title.style.color = 'red';
title.parentNode.removeChild(title);

Completa el código:

Change an element's style______
Remove an element______
Unlock with Premium

Interactive Test 2: Complete the Code

Rellena los huecos en cada casilla.

const title = document.getElementById('');
title..fontSize = '30px';
Unlock with Premium

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.

Enunciado:

* Escribe el código a continuación. Los caracteres correctos se mostrarán en verde y los incorrectos en rojo.

const title = document.querySelector('h1'); title.style.color = 'green'; const newP = document.createElement('p'); newP.textContent = 'Content added!'; document.body.appendChild(newP);
Unlock with Premium

Knowledge Check

Which method is used to add a newly created element to the DOM?


Unlock with Premium

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`.