
The DOM (Document Object Model) DOM manipulation is a programming interface that represents web documents as a tree structure of objects. JavaScript can interact with this tree to dynamically manipulate HTML content, styles, and structure.
1. Accessing Elements
Basic Selectors:
// By ID
const header = document.getElementById('header');
// By class name (returns HTMLCollection)
const items = document.getElementsByClassName('item');
// By tag name (returns HTMLCollection)
const paragraphs = document.getElementsByTagName('p');
// Modern selectors (returns NodeList)
const element = document.querySelector('#container .item');
const allElements = document.querySelectorAll('.items');
2. Manipulating Content
Text Content:
// Safe text manipulation
element.textContent = 'New text content';
// HTML content (beware of XSS vulnerabilities)
element.innerHTML = '<strong>Bold text</strong>';
Attributes:
// Get/set attributes
element.setAttribute('data-id', '123');
const id = element.getAttribute('data-id');
// Toggle boolean attributes
checkbox.checked = true;
Styles:
// Inline styles
element.style.color = 'red';
element.style.backgroundColor = '#fff';
// CSS Classes
element.classList.add('active');
element.classList.remove('inactive');
element.classList.toggle('hidden');
3. Creating Elements
// Create new element
const newDiv = document.createElement('div');
// Add content and attributes
newDiv.textContent = 'New element';
newDiv.className = 'box';
// Append to DOM
document.body.appendChild(newDiv);
// Insert before existing element
parent.insertBefore(newDiv, existingElement);
// Remove elements
parent.removeChild(elementToRemove);
4. Event Handling
// Basic event listener
button.addEventListener('click', function(e) {
console.log('Button clicked!', e.target);
});
// Event delegation
document.addEventListener('click', function(e) {
if(e.target.matches('.delete-btn')) {
e.target.parentElement.remove();
}
});
5. DOM Traversal
// Parent/child navigation
const parent = element.parentNode;
const children = element.childNodes;
// First/last child
const firstChild = parent.firstElementChild;
const lastChild = parent.lastElementChild;
// Sibling navigation
const nextSibling = element.nextElementSibling;
const prevSibling = element.previousElementSibling;
6. Performance Tips
- Batch DOM Updates
Use document fragments for multiple updates:
const fragment = document.createDocumentFragment();
for(let i = 0; i < 100; i++) {
const div = document.createElement('div');
fragment.appendChild(div);
}
document.body.appendChild(fragment);
- Debounce Scroll/Resize Events
window.addEventListener('resize', debounce(handleResize, 200));
function debounce(fn, delay) {
let timeout;
return function() {
clearTimeout(timeout);
timeout = setTimeout(fn, delay);
};
}
- Avoid Forced Synchronous Layouts
// Bad - multiple layout triggers
element.style.width = '100px';
const width = element.offsetWidth;
element.style.height = width + 'px';
// Good - batch style changes
element.style.cssText = 'width:100px; height:100px;';
7. Modern DOM APIs
Mutation Observer:
const observer = new MutationObserver(mutations => {
mutations.forEach(mutation => {
console.log('DOM changed:', mutation);
});
});
observer.observe(targetElement, {
attributes: true,
childList: true,
subtree: true
});
Element Dimensions:
// Get element dimensions
const rect = element.getBoundingClientRect();
console.log(rect.width, rect.height);
// Viewport-relative position
console.log(rect.top, rect.left);
Key Concepts:
- DOM Tree: Hierarchical representation of HTML elements
- Nodes: All elements, text, comments are nodes
- Live Collections:
getElementsBy*
methods return live collections - Virtual DOM: Optimization technique used by frameworks like React
Remember:
- DOM manipulation is relatively slow – minimize direct DOM operations
- Prefer CSS classes over inline styles for complex styling
- Use event delegation for dynamic elements
- Always sanitize user input before using
innerHTML
This comprehensive understanding of DOM manipulation will help you create dynamic, interactive web applications efficiently.