JavaScript DOM Manipulation

JavaScript DOM Manipulation

When you write JavaScript for web pages, you’ll often need to change the HTML and CSS dynamically. This is called DOM manipulation. The DOM (Document Object Model) is like a tree structure representing your HTML page.

What is the DOM?

The DOM is a programming interface for web documents. It represents the page as a tree of objects that you can modify with JavaScript. Each HTML element becomes a node in this tree.

Think of it like this: your HTML is the blueprint, and the DOM is the actual building that JavaScript can modify.

Selecting Elements

To change something, first select it. Here are common ways:

By ID

let header = document.getElementById('main-header');

By Class Name

let buttons = document.getElementsByClassName('btn');

By Tag Name

let paragraphs = document.getElementsByTagName('p');

By CSS Selector

let firstButton = document.querySelector('.btn');
let allButtons = document.querySelectorAll('.btn');

querySelector and querySelectorAll are the most flexible. They use the same selectors as CSS.

Changing Content

Once you have an element, you can change its text or HTML:

let title = document.getElementById('title');
title.textContent = 'New Title'; // Changes text only
title.innerHTML = '<strong>New Title</strong>'; // Allows HTML tags

textContent is safer for user input, innerHTML lets you add HTML.

Changing Styles

Modify CSS styles directly:

let box = document.getElementById('box');
box.style.backgroundColor = 'blue';
box.style.width = '200px';
box.style.height = '100px';

For multiple changes, use CSS classes:

// CSS
.highlight {
  background-color: yellow;
  font-weight: bold;
}

// JavaScript
let text = document.getElementById('important-text');
text.classList.add('highlight'); // Add class
text.classList.remove('highlight'); // Remove class
text.classList.toggle('highlight'); // Toggle on/off

Creating New Elements

You can create and add new elements to the page:

// Create element
let newParagraph = document.createElement('p');
newParagraph.textContent = 'This is a new paragraph';

// Add to page
let container = document.getElementById('container');
container.appendChild(newParagraph);

Other ways to add:

  • appendChild(): Adds as last child
  • insertBefore(): Adds before another element
  • prepend(): Adds as first child
  • after(): Adds after the element

Removing Elements

To remove an element:

let element = document.getElementById('to-remove');
element.remove(); // Modern way
// Or: element.parentNode.removeChild(element);

Working with Attributes

Get or set HTML attributes:

let link = document.getElementById('my-link');
link.href = 'https://example.com'; // Set attribute
let url = link.href; // Get attribute

link.setAttribute('target', '_blank'); // Another way to set
let target = link.getAttribute('target'); // Another way to get

Traversing the DOM

Move around the DOM tree:

let element = document.getElementById('start');

// Get parent
let parent = element.parentNode;

// Get children
let children = element.children;
let firstChild = element.firstElementChild;

// Get siblings
let nextSibling = element.nextElementSibling;
let prevSibling = element.previousElementSibling;

Practical Example

Here’s a simple example that creates a to-do list:

<div id="todo-app">
  <input type="text" id="todo-input" placeholder="Add a task">
  <button id="add-btn">Add</button>
  <ul id="todo-list"></ul>
</div>
let input = document.getElementById('todo-input');
let addBtn = document.getElementById('add-btn');
let list = document.getElementById('todo-list');

addBtn.addEventListener('click', function() {
  if (input.value.trim() !== '') {
    let li = document.createElement('li');
    li.textContent = input.value;
    
    // Add delete button
    let deleteBtn = document.createElement('button');
    deleteBtn.textContent = 'Delete';
    deleteBtn.addEventListener('click', function() {
      li.remove();
    });
    
    li.appendChild(deleteBtn);
    list.appendChild(li);
    input.value = '';
  }
});

This creates interactive web pages. For more on events, see JavaScript event handling.

DOM manipulation is key to modern web development. Practice by building small interactive components.

The MDN DOM reference has detailed documentation for all DOM methods.

Last updated on