Labs ICT
Pro Login

JavaScript DOM Manipulation: A Complete Guide

JavaScript Web Development 7 min read

The DOM is how JavaScript interacts with HTML. Learn to find, create, modify, and remove elements.

JavaScript DOM Manipulation: A Complete Guide

The DOM (Document Object Model) is how JavaScript interacts with HTML. Learning DOM manipulation lets you create dynamic, interactive web pages.

Finding Elements

// By ID
const header = document.getElementById('header');

// By CSS selector (first match)
const firstParagraph = document.querySelector('.intro');

// By CSS selector (all matches)
const allParagraphs = document.querySelectorAll('p');

// By class name
const items = document.getElementsByClassName('list-item');

Changing Content

// Change text
element.textContent = 'New text';

// Change HTML
element.innerHTML = '<strong>Bold text</strong>';

// Change attributes
element.setAttribute('href', 'https://example.com');
element.src = 'image.jpg';

Changing Styles

// Inline styles
element.style.color = 'blue';
element.style.fontSize = '20px';

// Add/remove classes
element.classList.add('active');
element.classList.remove('hidden');
element.classList.toggle('visible');

Creating Elements

// Create a new element
const newDiv = document.createElement('div');
newDiv.textContent = 'I was created!';
newDiv.classList.add('card');

// Add to the page
document.body.appendChild(newDiv);

// Insert before another element
parent.insertBefore(newDiv, referenceElement);

Removing Elements

// Remove an element
element.remove();

// Or remove from parent
parent.removeChild(element);

Event Listeners

// Click event
button.addEventListener('click', () => {
  alert('Button clicked!');
});

// Form submission
form.addEventListener('submit', (e) => {
  e.preventDefault(); // Stop page reload
  const data = new FormData(form);
});

// Keyboard events
document.addEventListener('keydown', (e) => {
  console.log(e.key);
});

Building a To-Do List

const input = document.querySelector('input');
const button = document.querySelector('button');
const list = document.querySelector('ul');

button.addEventListener('click', () => {
  const li = document.createElement('li');
  li.textContent = input.value;
  list.appendChild(li);
  input.value = '';
});

Note: DOM manipulation is the foundation of frontend development. Master these basics before moving to frameworks like React.