Hiprup

What is the DOM and how do you manipulate it?

The DOM (Document Object Model) is a tree representation of the page that JavaScript can read and change to make it interactive.

  • Selecting — querySelector and querySelectorAll find elements using CSS selectors.

  • Changing — update textContent, attributes, classes (classList), or styles.

  • Structure — create, append, and remove nodes.

  • Events — respond to user actions with addEventListener.

Performance tip: minimise direct DOM changes — batch updates or build off-screen, since layout work is expensive.

// Selecting
const el = document.getElementById('app');
const btn = document.querySelector('.submit-btn');
const items = document.querySelectorAll('.item'); // NodeList

// Modifying
el.textContent = 'New text';            // Safe (no HTML parsing)
el.innerHTML = '<strong>Bold</strong>';  // Parses HTML (XSS risk!)
el.classList.add('active');
el.classList.toggle('visible');
el.style.color = 'red';                  // Inline style
el.setAttribute('aria-label', 'Menu');

// Creating elements
const li = document.createElement('li');
li.textContent = 'New item';
li.className = 'item';
li.dataset.id = '42';  // data-id="42"
document.querySelector('ul').appendChild(li);

// Document fragment (batch — one DOM update)
const fragment = document.createDocumentFragment();
for (let i = 0; i < 100; i++) {
  const item = document.createElement('div');
  item.textContent = `Item ${i}`;
  fragment.appendChild(item); // No DOM update yet
}
document.getElementById('list').appendChild(fragment); // One update!

// Modern methods
el.remove();                    // Remove element
parent.append(child1, child2);  // Append multiple
parent.prepend(child);          // Insert at beginning
el.replaceWith(newEl);          // Replace

querySelector uses CSS selectors (most flexible). textContent is safe (no XSS), innerHTML parses HTML (XSS risk with user input). classList manipulates CSS classes. createElement + appendChild adds new elements. DocumentFragment batches 100 DOM operations into one update (major performance improvement).

Modern methods (append, prepend, remove) are cleaner than older APIs.

Know querySelector (modern selection), textContent vs innerHTML (security), classList (CSS classes), and createElement (dynamic elements). DocumentFragment for batch operations shows performance awareness. innerHTML is an XSS risk with user input — mention this.

What is the DOM and how do you manipulate it? | Hiprup