JavaScript DOM Manipulation - Complete Guide to Dynamic Web Content
Introduction: The Document Object Model (DOM) is a programming interface for web documents. It represents the page so that programs can change the document structure, style, and content. DOM manipulation allows JavaScript to dynamically modify web pages.
1. DOM Selection Methods
Selecting elements is the first step in DOM manipulation:
// Select by ID
const element = document.getElementById('myId');
// Select by class name (returns HTMLCollection)
const elements = document.getElementsByClassName('myClass');
// Select by tag name
const paragraphs = document.getElementsByTagName('p');
Common properties and methods for DOM manipulation:
Property/Method
Description
Example
innerHTML
Gets/sets HTML content
element.innerHTML = '<p>New content</p>';
textContent
Gets/sets text content
element.textContent = 'Plain text';
style
Accesses inline styles
element.style.color = 'red';
className
Gets/sets class attribute
element.className = 'newClass';
classList
Manages CSS classes
element.classList.add('active');
setAttribute()
Sets attribute value
element.setAttribute('title', 'Tooltip');
addEventListener()
Adds event listener
button.addEventListener('click', handler);
3. Modifying Element Content
Changing text and HTML content:
Original content will be changed by JavaScript
function modifyContent() {
const element = document.getElementById('content-demo');
element.innerHTML = '<p>Content modified by JavaScript!</p>';
}
function modifyStyle() {
const element = document.getElementById('content-demo');
element.style.backgroundColor = '#f1c40f';
element.style.padding = '10px';
element.style.borderRadius = '5px';
}
4. Working with CSS Classes
Using classList for efficient styling:
This element will have classes added/removed
function addClass() {
const element = document.getElementById('class-demo');
element.classList.add('highlight');
}
function removeClass() {
const element = document.getElementById('class-demo');
element.classList.remove('highlight');
}
function toggleClass() {
const element = document.getElementById('class-demo');
element.classList.toggle('highlight');
}
// Other classList methods
element.classList.contains('className'); // Check if class exists
element.classList.replace('oldClass', 'newClass'); // Replace a class
5. Creating and Removing Elements
Dynamic element creation and removal:
// Creating elements
function createElement() {
const container = document.getElementById('dynamic-container');
const newElement = document.createElement('div');
newElement.textContent = 'Dynamically created element';
newElement.className = 'dynamic-element';
container.appendChild(newElement);
}
// Removing elements
function removeElement() {
const container = document.getElementById('dynamic-container');
if (container.lastChild) {
container.removeChild(container.lastChild);
}
}
// Finding elements
const allLis = document.querySelectorAll('li'); // All list items
const parentUl = target.closest('ul'); // Closest parent ul
9. Performance Considerations
Optimizing DOM manipulation for better performance:
// Inefficient: Multiple DOM queries and modifications
const items = document.querySelectorAll('.item');
for (let i = 0; i < items.length; i++) {
items[i].style.color = 'red';
items[i].style.fontSize = '16px';
}
// Efficient: Batch operations and document fragments
const fragment = document.createDocumentFragment();
const newItems = [];
for (let i = 0; i < 100; i++) {
const item = document.createElement('div');
item.textContent = `Item ${i + 1}`;
item.style.cssText = 'color: red; font-size: 16px;';
newItems.push(item);
}
// Append all at once
newItems.forEach(item => fragment.appendChild(item));
document.getElementById('container').appendChild(fragment);
// Use CSS classes instead of inline styles when possible
element.classList.add('styled-item'); // Better than setting style properties
Performance Tip: Minimize DOM queries and batch DOM modifications when possible. Cache DOM references and use CSS classes instead of inline styles for better performance.
10. Best Practices
Cache DOM element references in variables to avoid repeated queries
Use event delegation for multiple similar elements
Prefer querySelector and querySelectorAll over older methods
Use CSS classes instead of inline styles for better maintainability
Consider using requestAnimationFrame for smooth animations
Always validate user input before inserting into the DOM to prevent XSS
Use document.createDocumentFragment() for batch DOM operations
Remember to remove event listeners when elements are removed