DOM Manipulation
Query, modify, and interact with HTML elements using JavaScript
#dom #elements #events #query
DOM Manipulation
Interact with HTML elements using JavaScript DOM APIs.
Selecting Elements
// By ID
const header = document.getElementById('header');
// By class name
const buttons = document.getElementsByClassName('btn');
// By tag name
const paragraphs = document.getElementsByTagName('p');
// Query selector (modern, recommended)
const firstButton = document.querySelector('.btn');
const allButtons = document.querySelectorAll('.btn');
Modifying Content
const element = document.querySelector('#message');
// Change text content
element.textContent = 'Hello, World!';
// Change HTML content
element.innerHTML = '<strong>Bold text</strong>';
// Change attributes
element.setAttribute('data-id', '123');
const id = element.getAttribute('data-id');
// Change CSS classes
element.classList.add('active');
element.classList.remove('hidden');
element.classList.toggle('highlight');
Modifying Styles
const box = document.querySelector('.box');
// Direct style manipulation
box.style.backgroundColor = 'blue';
box.style.width = '200px';
box.style.padding = '20px';
// CSS properties with hyphens use camelCase
box.style.borderRadius = '10px';
Creating and Adding Elements
// Create new element
const newDiv = document.createElement('div');
newDiv.textContent = 'New element';
newDiv.classList.add('item');
// Append to parent
const container = document.querySelector('#container');
container.appendChild(newDiv);
// Insert before another element
const firstChild = container.firstChild;
container.insertBefore(newDiv, firstChild);
// Modern methods
container.append(newDiv); // Adds at end
container.prepend(newDiv); // Adds at start
Removing Elements
const element = document.querySelector('.to-remove');
// Remove element
element.remove();
// Or remove from parent
element.parentNode.removeChild(element);
Event Handling
const button = document.querySelector('#myButton');
// Add event listener
button.addEventListener('click', (event) => {
console.log('Button clicked!');
console.log('Target:', event.target);
});
// Event with options
button.addEventListener('click', handler, {
once: true, // Run only once
passive: true // Improve scroll performance
});
// Remove event listener
function handler(event) {
console.log('Clicked');
}
button.addEventListener('click', handler);
button.removeEventListener('click', handler);
Event Delegation
// Handle clicks on dynamically added elements
const list = document.querySelector('#list');
list.addEventListener('click', (event) => {
if (event.target.matches('.list-item')) {
console.log('Item clicked:', event.target.textContent);
}
});
Form Handling
const form = document.querySelector('#myForm');
const input = document.querySelector('#nameInput');
form.addEventListener('submit', (event) => {
event.preventDefault(); // Prevent page reload
const value = input.value;
console.log('Submitted:', value);
// Clear form
form.reset();
});
// Input validation
input.addEventListener('input', (event) => {
const value = event.target.value;
if (value.length < 3) {
input.setCustomValidity('Must be at least 3 characters');
} else {
input.setCustomValidity('');
}
});
Traversing the DOM
const element = document.querySelector('.current');
// Parent
const parent = element.parentElement;
// Children
const children = element.children; // HTMLCollection
const firstChild = element.firstElementChild;
const lastChild = element.lastElementChild;
// Siblings
const nextSibling = element.nextElementSibling;
const prevSibling = element.previousElementSibling;
// Find closest ancestor matching selector
const container = element.closest('.container');
Working with Data Attributes
const element = document.querySelector('.product');
// Set data attribute
element.dataset.productId = '12345';
element.dataset.price = '99.99';
// Read data attribute
console.log(element.dataset.productId); // 12345
// In HTML: <div class="product" data-product-id="12345" data-price="99.99"></div>
Discover another handy tool from EditPDF.pro