JavaScript logoJavaScript vES6+BEGINNER

DOM Manipulation

Essential DOM manipulation techniques with vanilla JavaScript

7 min read
domjavascripthtmlbrowserevents

Element Selection

Query Selectors

Select elements using CSS selectors for flexible element targeting

javascript
💡 querySelector uses CSS selector syntax
⚡ getElementById is faster for IDs
📌 querySelectorAll returns NodeList, not Array
✅ Always check if element exists before using

Get Element Methods

Traditional DOM methods for selecting elements by ID, class, or tag

javascript
💡 getElementById is the fastest selection method
⚠️ HTMLCollection is live and updates automatically
📌 No # or . prefix needed for getElementById/ClassName
✅ Convert to array for array methods

Creating Elements

createElement & cloneNode

Create new elements or clone existing ones programmatically

javascript
💡 Set properties before adding to DOM for performance
⚡ Use DocumentFragment for adding multiple elements
📌 cloneNode(true) for deep clone with children
✅ Template elements are great for complex HTML

innerHTML & insertAdjacentHTML

Insert HTML content directly into elements using string templates

javascript
⚠️ innerHTML can cause XSS vulnerabilities with user input
💡 insertAdjacentHTML preserves existing content and event listeners
⚡ Building HTML strings is faster for many elements
✅ Use textContent for user input to prevent XSS

Modifying Elements

Text & HTML Content

Modify the text and HTML content of elements safely

javascript
💡 textContent is safe from XSS attacks
⚠️ innerHTML removes existing event listeners
📌 innerText respects CSS visibility
✅ Always use textContent for user input

Attributes & Properties

Get, set, and remove HTML attributes and DOM properties

javascript
💡 Properties are faster than attributes for common values
📌 Data attributes are accessed via dataset property
⚠️ Attribute values are always strings
✅ Use properties for boolean values (checked, disabled)

Styling & Classes

classList Methods

Manage CSS classes on elements with the classList API

javascript
💡 classList is more efficient than className manipulation
⚡ Can add/remove multiple classes at once
📌 toggle() returns true if class was added, false if removed
✅ classList.contains() is cleaner than string searching

Inline Styles

Directly manipulate element styles through the style property

javascript
💡 Style properties use camelCase (backgroundColor)
⚠️ Inline styles have high specificity
📌 getComputedStyle returns resolved values
✅ Prefer CSS classes over inline styles

DOM Traversal

Parent & Child Navigation

Navigate between parent and child elements in the DOM tree

javascript
💡 children returns only elements, childNodes includes text
📌 closest() is great for event delegation
⚡ parentElement is null for document
✅ Use contains() to check relationships

Sibling Navigation

Navigate between sibling elements at the same DOM level

javascript
💡 ElementSibling properties skip text nodes
📌 Sibling properties return null at boundaries
⚡ Cache parent.children for multiple operations
✅ Filter self out when getting all siblings

Adding & Removing

Adding Elements

Add elements to the DOM using various insertion methods

javascript
💡 appendChild moves elements, doesn't copy
⚡ Use DocumentFragment for batch inserts
📌 append() can add multiple items and text
✅ insertAdjacentElement preserves element position

Removing Elements

Remove elements from the DOM or replace them with new ones

javascript
💡 remove() is simpler than removeChild()
⚠️ innerHTML = "" removes event listeners
📌 replaceWith() can replace with multiple items
✅ Always check element exists before removing

Events - Basics

Event Listeners

Attach and remove event handlers to respond to user interactions

javascript
💡 Named functions can be removed, anonymous cannot
⚡ Use passive: true for scroll/touch events
📌 Arrow functions don't have their own "this"
✅ Use AbortController for multiple listener cleanup

Event Object

Access event properties and control event behavior

javascript
💡 target vs currentTarget is important for delegation
⚠️ preventDefault doesn't stop propagation
📌 Use event.key for keyboard events, not keyCode
✅ Check cancelable before calling preventDefault

Events - Advanced

Event Delegation

Handle events efficiently using event bubbling and delegation

javascript
💡 Delegation works for dynamically added elements
⚡ One listener is better than many
📌 Use closest() for complex component structures
✅ Check event.target existence in delegated handlers

Custom Events

Create and dispatch custom events for component communication

javascript
💡 CustomEvent can carry data in detail property
📌 Namespace events to avoid conflicts
⚡ Use bubbles: true for component communication
✅ Document can serve as a global event bus

Forms

Form Elements & Data

Access and manipulate form elements and their values

javascript
💡 FormData makes form handling much easier
📌 form.elements provides easy access to inputs
⚡ Use checkValidity() for HTML5 validation
✅ Always preventDefault() on form submit for SPA

Form Events

Handle form-specific events for validation and interaction

javascript
💡 input event for real-time, change for final value
📌 focusin/focusout bubble, focus/blur don't
⚠️ Prevent invalid event to show custom messages
✅ Debounce validation for better performance

Modern DOM APIs

Intersection Observer

Efficiently detect when elements enter or leave the viewport

javascript
💡 More efficient than scroll event listeners
⚡ Great for lazy loading and animations
📌 Can observe multiple elements with one observer
✅ Always disconnect when done observing

Mutation Observer

Watch for changes to the DOM tree and element attributes

javascript
💡 Can detect any DOM change
⚠️ Be careful with subtree: true on large DOMs
📌 Use takeRecords() to get pending mutations
✅ Always disconnect when no longer needed