DOM Manipulation

Essential DOM methods, events, and manipulation techniques

Element Selection

getElementById()

Select element by ID

const element = document.getElementById("myId");

querySelector()

Select first matching element

const element = document.querySelector(".myClass");

querySelectorAll()

Select all matching elements

const elements = document.querySelectorAll("p");

getElementsByClassName()

Select elements by class

const elements = document.getElementsByClassName("myClass");

getElementsByTagName()

Select elements by tag

const elements = document.getElementsByTagName("div");

Element Creation & Manipulation

createElement()

Create new element

const div = document.createElement("div");

createTextNode()

Create text node

const text = document.createTextNode("Hello");

appendChild()

Add child to element

parent.appendChild(child);

removeChild()

Remove child from element

parent.removeChild(child);

replaceChild()

Replace child element

parent.replaceChild(newChild, oldChild);

insertBefore()

Insert element before reference

parent.insertBefore(newElement, referenceElement);

Element Properties

innerHTML

Get/set HTML content

element.innerHTML = "<p>New content</p>";

textContent

Get/set text content

element.textContent = "Plain text";

innerText

Get/set visible text

element.innerText = "Visible text";

className

Get/set CSS classes

element.className = "class1 class2";

classList

Manipulate CSS classes

element.classList.add("newClass");

style

Access inline styles

element.style.backgroundColor = "red";

Attributes & Data

getAttribute()

Get attribute value

const value = element.getAttribute("data-id");

setAttribute()

Set attribute value

element.setAttribute("data-id", "123");

removeAttribute()

Remove attribute

element.removeAttribute("data-id");

hasAttribute()

Check if attribute exists

const hasId = element.hasAttribute("id");

dataset

Access data attributes

const value = element.dataset.userId;

Element Traversal

parentElement

Get parent element

const parent = element.parentElement;

children

Get child elements

const children = element.children;

firstElementChild

Get first child element

const first = element.firstElementChild;

lastElementChild

Get last child element

const last = element.lastElementChild;

nextElementSibling

Get next sibling

const next = element.nextElementSibling;

previousElementSibling

Get previous sibling

const prev = element.previousElementSibling;

Event Listeners

addEventListener()

Add event listener

element.addEventListener("click", handleClick);

removeEventListener()

Remove event listener

element.removeEventListener("click", handleClick);

dispatchEvent()

Trigger custom event

element.dispatchEvent(new Event("custom"));

Common Events

click

Mouse click event

element.addEventListener("click", (e) => console.log("clicked"));

dblclick

Double click event

element.addEventListener("dblclick", handleDoubleClick);

mouseenter

Mouse enter element

element.addEventListener("mouseenter", handleMouseEnter);

mouseleave

Mouse leave element

element.addEventListener("mouseleave", handleMouseLeave);

keydown

Key press down

element.addEventListener("keydown", handleKeyDown);

keyup

Key release

element.addEventListener("keyup", handleKeyUp);

submit

Form submission

form.addEventListener("submit", handleSubmit);

change

Input value change

input.addEventListener("change", handleChange);

focus

Element gains focus

input.addEventListener("focus", handleFocus);

blur

Element loses focus

input.addEventListener("blur", handleBlur);

Common Patterns

Dynamic Content Creation

Creating and manipulating DOM elements

// Create a new list item
function createListItem(text) {
  const li = document.createElement('li');
  li.textContent = text;
  li.className = 'list-item';
  
  // Add click event
  li.addEventListener('click', () => {
    li.classList.toggle('selected');
  });
  
  return li;
}

// Add items to a list
const list = document.getElementById('myList');
const items = ['Item 1', 'Item 2', 'Item 3'];

items.forEach(item => {
  const li = createListItem(item);
  list.appendChild(li);
});

Event Delegation

Handling events on dynamically created elements

// Event delegation for dynamic content
document.getElementById('container').addEventListener('click', (e) => {
  // Check if clicked element is a button
  if (e.target.matches('.btn')) {
    console.log('Button clicked:', e.target.textContent);
  }
  
  // Check if clicked element is inside a card
  if (e.target.closest('.card')) {
    const card = e.target.closest('.card');
    console.log('Card clicked:', card.dataset.id);
  }
});

Form Handling

Complete form handling with validation

const form = document.getElementById('myForm');

form.addEventListener('submit', (e) => {
  e.preventDefault();
  
  const formData = new FormData(form);
  const data = Object.fromEntries(formData);
  
  // Validation
  if (!data.email || !data.email.includes('@')) {
    showError('Please enter a valid email');
    return;
  }
  
  // Submit data
  submitForm(data);
});

function showError(message) {
  const errorDiv = document.getElementById('error');
  errorDiv.textContent = message;
  errorDiv.style.display = 'block';
}

DOM Traversal

Navigating through DOM elements

// Find all buttons within a specific container
const container = document.querySelector('.container');
const buttons = container.querySelectorAll('button');

// Find parent with specific class
function findParentWithClass(element, className) {
  let parent = element.parentElement;
  
  while (parent) {
    if (parent.classList.contains(className)) {
      return parent;
    }
    parent = parent.parentElement;
  }
  
  return null;
}

// Get all siblings of an element
function getSiblings(element) {
  const siblings = [];
  let sibling = element.parentElement.firstElementChild;
  
  while (sibling) {
    if (sibling !== element) {
      siblings.push(sibling);
    }
    sibling = sibling.nextElementSibling;
  }
  
  return siblings;
}

Element Animation

Creating smooth element animations

// Fade in element
function fadeIn(element, duration = 300) {
  element.style.opacity = '0';
  element.style.display = 'block';
  
  let start = performance.now();
  
  function animate(currentTime) {
    const elapsed = currentTime - start;
    const progress = Math.min(elapsed / duration, 1);
    
    element.style.opacity = progress;
    
    if (progress < 1) {
      requestAnimationFrame(animate);
    }
  }
  
  requestAnimationFrame(animate);
}

// Slide down element
function slideDown(element, duration = 300) {
  element.style.height = '0px';
  element.style.overflow = 'hidden';
  element.style.display = 'block';
  
  const targetHeight = element.scrollHeight;
  let start = performance.now();
  
  function animate(currentTime) {
    const elapsed = currentTime - start;
    const progress = Math.min(elapsed / duration, 1);
    
    element.style.height = (targetHeight * progress) + 'px';
    
    if (progress < 1) {
      requestAnimationFrame(animate);
    } else {
      element.style.height = 'auto';
    }
  }
  
  requestAnimationFrame(animate);
}

Tips & Best Practices

Use querySelector for single elements and querySelectorAll for multiple

Always remove event listeners to prevent memory leaks

Use event delegation for dynamically created elements

Prefer textContent over innerHTML for security

Use classList methods instead of manipulating className