DOM Manipulation
DOM manipulation cheat sheet with selectors, event handling, element creation, traversal, and vanilla JavaScript code examples.

PDF · 2 pages
DOM Manipulation PDF cheat sheet
A two-page DOM Manipulation reference for printing or offline use.
Other JavaScript Sheets
Element Selection
Select elements using CSS selectors for flexible element targeting
// Select first matching element
const element = document.querySelector('.class-name')
const element = document.querySelector('#id')
const element = document.querySelector('[data-id="123"]')
// Select all matching elements (returns NodeList)
const elements = document.querySelectorAll('.class-name')
const elements = document.querySelectorAll('div.active')
const elements = document.querySelectorAll('[type="checkbox"]:checked')
// Convert NodeList to Array
const array = Array.from(document.querySelectorAll('.item'))
const array = [...document.querySelectorAll('.item')]Traditional DOM methods for selecting elements by ID, class, or tag
// Get single element by ID (fastest)
const element = document.getElementById('header')
// Get elements by class (returns live HTMLCollection)
const elements = document.getElementsByClassName('item')
// Get elements by tag name (returns live HTMLCollection)
const elements = document.getElementsByTagName('div')
// Get elements by name attribute (forms)
const elements = document.getElementsByName('email')Creating Elements
Create new elements or clone existing ones programmatically
// Create new element
const div = document.createElement('div')
div.className = 'card'
div.textContent = 'Hello World'
// Clone existing element
const original = document.querySelector('.card')
const clone = original.cloneNode(true) // true = deep clone
// Create with attributes
const link = document.createElement('a')
link.href = 'https://example.com'
link.textContent = 'Click me'
link.target = '_blank'Insert HTML content directly into elements using string templates
// Set innerHTML (replaces all content)
element.innerHTML = '<p>New content</p>'
// Append HTML (preserves existing)
element.insertAdjacentHTML('beforeend', '<p>Added paragraph</p>')
// Insert at different positions
element.insertAdjacentHTML('beforebegin', '<p>Before element</p>')
element.insertAdjacentHTML('afterbegin', '<p>First child</p>')
element.insertAdjacentHTML('beforeend', '<p>Last child</p>')
element.insertAdjacentHTML('afterend', '<p>After element</p>')Modifying Elements
Modify the text and HTML content of elements safely
// Text content (safe, escapes HTML)
element.textContent = 'Hello World'
const text = element.textContent
// Inner text (respects styling)
element.innerText = 'Visible text only'
const visible = element.innerText
// HTML content (parses HTML)
element.innerHTML = '<strong>Bold text</strong>'
const html = element.innerHTML
// Outer HTML (includes element itself)
element.outerHTML = '<div>Replacement</div>'Get, set, and remove HTML attributes and DOM properties
// Set attribute
element.setAttribute('data-id', '123')
element.setAttribute('disabled', '')
// Get attribute
const id = element.getAttribute('data-id')
const href = link.getAttribute('href')
// Remove attribute
element.removeAttribute('disabled')
element.removeAttribute('data-id')
// Check attribute
if (element.hasAttribute('disabled')) {
// Element is disabled
}Styling & Classes
Manage CSS classes on elements with the classList API
// Add class
element.classList.add('active')
element.classList.add('highlight', 'large')
// Remove class
element.classList.remove('active')
element.classList.remove('highlight', 'large')
// Toggle class
element.classList.toggle('visible')
// Check class
if (element.classList.contains('active')) {
// Has active class
}
// Replace class
element.classList.replace('old-class', 'new-class')Directly manipulate element styles through the style property
// Set individual styles
element.style.color = 'red'
element.style.backgroundColor = '#f0f0f0'
element.style.fontSize = '16px'
// Set multiple styles
Object.assign(element.style, {
color: 'blue',
fontSize: '20px',
margin: '10px'
})
// Remove style
element.style.color = ''
element.style.removeProperty('background-color')
// Get computed styles
const styles = window.getComputedStyle(element)
const color = styles.getPropertyValue('color')DOM Traversal
Navigate between parent and child elements in the DOM tree
// Parent access
const parent = element.parentElement
const parentNode = element.parentNode
// Children access
const children = element.children // HTMLCollection
const childNodes = element.childNodes // NodeList (includes text)
// First and last child
const first = element.firstElementChild
const last = element.lastElementChild
// Check for children
if (element.hasChildNodes()) {
// Has child nodes
}Navigate between sibling elements at the same DOM level
// Next sibling
const next = element.nextElementSibling
const nextNode = element.nextSibling // Can be text
// Previous sibling
const prev = element.previousElementSibling
const prevNode = element.previousSibling
// All siblings
const parent = element.parentElement
const siblings = Array.from(parent.children)
.filter(child => child !== element)Adding & Removing
Add elements to the DOM using various insertion methods
// Append as last child
parent.appendChild(element)
parent.append(element, 'text', element2)
// Prepend as first child
parent.prepend(element)
parent.insertBefore(element, parent.firstChild)
// Insert at specific position
parent.insertBefore(newElement, referenceElement)
// Insert adjacent to element
element.insertAdjacentElement('afterend', newElement)Remove elements from the DOM or replace them with new ones
// Remove element (modern)
element.remove()
// Remove child (classic)
parent.removeChild(child)
// Replace element
oldElement.replaceWith(newElement)
parent.replaceChild(newElement, oldElement)
// Clear all children
parent.innerHTML = ''
parent.textContent = ''Events - Basics
Attach and remove event handlers to respond to user interactions
// Add event listener
element.addEventListener('click', handleClick)
// With options
element.addEventListener('scroll', handleScroll, {
passive: true,
once: true
})
// Remove event listener
element.removeEventListener('click', handleClick)
// Event handler function
function handleClick(event) {
console.log('Clicked!', event.target)
}Access event properties and control event behavior
// Event properties
function handleClick(event) {
event.target // Element that triggered event
event.currentTarget // Element with listener
event.type // Event type (e.g., 'click')
event.timeStamp // When event occurred
// Prevent default action
event.preventDefault()
// Stop propagation
event.stopPropagation()
}Events - Advanced
Handle events efficiently using event bubbling and delegation
// Delegate events to parent
document.addEventListener('click', (event) => {
if (event.target.matches('.button')) {
// Handle button click
}
})
// Closest for complex structures
list.addEventListener('click', (event) => {
const item = event.target.closest('.item')
if (item) {
// Handle item click
}
})Create and dispatch custom events for component communication
// Create custom event
const event = new CustomEvent('user-login', {
detail: { userId: 123, username: 'john' },
bubbles: true
})
// Dispatch event
element.dispatchEvent(event)
// Listen for custom event
element.addEventListener('user-login', (event) => {
console.log('User logged in:', event.detail)
})Forms
Access and manipulate form elements and their values
// Get form and elements
const form = document.getElementById('myForm')
const input = form.elements['username']
const inputs = form.elements // All form controls
// Get values
const value = input.value
const checked = checkbox.checked
const selected = select.value
// FormData API
const formData = new FormData(form)
const username = formData.get('username')Handle form-specific events for validation and interaction
// Form events
form.addEventListener('submit', handleSubmit)
form.addEventListener('reset', handleReset)
// Input events
input.addEventListener('input', handleInput) // On every change
input.addEventListener('change', handleChange) // On blur if changed
input.addEventListener('focus', handleFocus)
input.addEventListener('blur', handleBlur)
// Validation events
input.addEventListener('invalid', handleInvalid)Modern DOM APIs
Efficiently detect when elements enter or leave the viewport
// Create observer
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.classList.add('visible')
}
})
})
// Observe elements
document.querySelectorAll('.lazy').forEach(el => {
observer.observe(el)
})
// Stop observing
observer.unobserve(element)
observer.disconnect()Watch for changes to the DOM tree and element attributes
// Create observer
const observer = new MutationObserver((mutations) => {
mutations.forEach(mutation => {
console.log('Type:', mutation.type)
console.log('Target:', mutation.target)
})
})
// Observe element
observer.observe(element, {
childList: true, // Child changes
attributes: true, // Attribute changes
subtree: true // All descendants
})
// Stop observing
observer.disconnect()