DOM Manipulation

✨ Creating New Elements

JavaScript allows you to create new HTML elements dynamically and add them to the DOM. This is essential for building interactive web applications.

JavaScript Editor
Creation Methods:
  • createElement(tagName) - Creates new element
  • createTextNode(text) - Creates text node
  • createDocumentFragment() - Lightweight DOM container
Insertion Methods:
  • appendChild(node) - Adds as last child
  • insertBefore(new, reference) - Inserts before element
  • insertAdjacentElement(position, element) - Flexible insertion

🎨 Modifying Existing Elements

You can modify element content, styles, classes, and attributes to create dynamic user interfaces that respond to user interactions.

JavaScript Editor
Content Modification:
  • textContent - Plain text
  • innerHTML - HTML content
  • innerText - Visible text (slower)
Class Management:
  • classList.add() - Add classes
  • classList.remove() - Remove classes
  • classList.toggle() - Toggle classes
  • classList.contains() - Check class
Style Management:
  • element.style.property - Inline styles
  • setAttribute('style', '...')
  • cssText - Batch style changes

🗑️ Removing and Replacing Elements

Removing elements from the DOM is just as important as creating them. This helps maintain clean, efficient, and user-friendly interfaces.

JavaScript Editor
💡 Performance Tip:

When removing multiple children, use while (element.firstChild) loop instead of multiple removeChild() calls for better performance. Or use element.innerHTML = '' for simple cases.

📱 Practical Application: Todo List

Let's build a complete Todo List application using DOM manipulation techniques. This practical example demonstrates real-world usage of creating, modifying, and removing elements.

JavaScript Editor
🚀 Enhanced Features to Try:
  1. Add localStorage to save tasks between page reloads
  2. Implement drag-and-drop to reorder tasks
  3. Add due dates and priority levels to tasks
  4. Create filters (All/Active/Completed)
  5. Add task editing functionality

📋 DOM Manipulation Best Practices

Performance Tips:
  • Minimize DOM access (cache references)
  • Use DocumentFragment for multiple inserts
  • Batch style changes
  • Use event delegation
Security Tips:
  • Avoid innerHTML with user input
  • Use textContent for plain text
  • Sanitize HTML before insertion
  • Validate all user inputs
Common Methods:
  • cloneNode() - Clone elements
  • contains() - Check if contains node
  • matches() - Check if matches selector
  • getBoundingClientRect() - Get position