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.
Creation Methods:
createElement(tagName)- Creates new elementcreateTextNode(text)- Creates text nodecreateDocumentFragment()- Lightweight DOM container
Insertion Methods:
appendChild(node)- Adds as last childinsertBefore(new, reference)- Inserts before elementinsertAdjacentElement(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.
Content Modification:
textContent- Plain textinnerHTML- HTML contentinnerText- Visible text (slower)
Class Management:
classList.add()- Add classesclassList.remove()- Remove classesclassList.toggle()- Toggle classesclassList.contains()- Check class
Style Management:
element.style.property- Inline stylessetAttribute('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.
💡 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.
🚀 Enhanced Features to Try:
- Add localStorage to save tasks between page reloads
- Implement drag-and-drop to reorder tasks
- Add due dates and priority levels to tasks
- Create filters (All/Active/Completed)
- 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 elementscontains()- Check if contains nodematches()- Check if matches selectorgetBoundingClientRect()- Get position