Chapters: JavaScript HTML & CSS JSON XML YAML Go Java ← Full TOC

← JavaScript Index

🌐 DOM & Browser — DOM manipulation, events, localStorage, fetch in browser

The Document Object Model (DOM) is the browser's in-memory representation of HTML. JavaScript manipulates the DOM to create interactive web pages. All DOM operations are browser-only — not available in Node.js.

📋 Methods & APIs

NameSignature / SyntaxDescription
document.querySelectordocument.querySelector(css) → ElementSelect first matching element
document.querySelectorAlldocument.querySelectorAll(css) → NodeListSelect all matching elements
document.getElementByIddocument.getElementById(id) → ElementSelect element by ID
document.createElementdocument.createElement(tag) → ElementCreate new DOM element
element.innerHTMLelement.innerHTML = '<b>text</b>'Set/get HTML content (careful: XSS risk)
element.textContentelement.textContent = 'text'Set/get text content (safe, no HTML parsing)
element.setAttributeelement.setAttribute(name, value)Set attribute value
element.getAttributeelement.getAttribute(name) → stringGet attribute value
element.classList.addelement.classList.add('active')Add CSS class
element.classList.removeelement.classList.remove('active')Remove CSS class
element.classList.toggleelement.classList.toggle('dark')Toggle CSS class
element.classList.containselement.classList.contains('x') → boolCheck if class present
element.styleelement.style.color = 'red'Set inline CSS
element.appendChildparent.appendChild(child)Append child node
element.removeelement.remove()Remove element from DOM
element.insertAdjacentHTMLel.insertAdjacentHTML('beforeend', html)Insert HTML at position
addEventListenerel.addEventListener('click', fn)Attach event listener
removeEventListenerel.removeEventListener('click', fn)Remove event listener
event.preventDefaultevent.preventDefault()Prevent default browser behavior
event.stopPropagationevent.stopPropagation()Stop event bubbling
localStorage.setItemlocalStorage.setItem('key', JSON.stringify(val))Persist data across sessions
localStorage.getItemJSON.parse(localStorage.getItem('key'))Retrieve persisted data
sessionStoragesessionStorage.setItem/getItem(...)Session-scoped storage
window.locationwindow.location.href = urlNavigate to URL
window.historywindow.history.pushState(state, '', path)SPA routing without reload
IntersectionObservernew IntersectionObserver(fn, opts)Detect element visibility
MutationObservernew MutationObserver(fn)Watch DOM changes
ResizeObservernew ResizeObserver(fn)Watch element size changes
requestAnimationFramerequestAnimationFrame(fn)Run fn before next repaint (animations)

💡 Example

Run with node script.js or save as HTML and open in browser.

// DOM Manipulation — save as index.html and open in browser
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JS DOM Demo | MyWebUniversity</title>
  <style>
    body { font-family: Arial; max-width: 600px; margin: 40px auto;
           background: #0f172a; color: #e5e7eb; padding: 20px; }
    .card { background: #1e293b; border: 1px solid #334155;
            border-radius: 8px; padding: 16px; margin: 8px 0; }
    .card.highlight { border-color: #facc15; }
    button { padding: 8px 16px; background: #ca8a04; color: #fff;
             border: none; border-radius: 4px; cursor: pointer; margin: 4px; }
    #score { font-size: 2em; color: #facc15; text-align: center; padding: 10px; }
  </style>
</head>
<body>
  <h1>JS DOM Demo</h1>
  <div id="score">0</div>
  <button id="inc">+1</button>
  <button id="dec">-1</button>
  <button id="reset">Reset</button>
  <div id="list"></div>
  <input id="newItem" placeholder="Add item..." style="padding:8px;margin:8px 0;width:200px">
  <button id="add">Add</button>

  <script>
    // Counter with localStorage persistence
    let count = parseInt(localStorage.getItem('count') || '0');
    const scoreEl = document.getElementById('score');
    const update = () => { scoreEl.textContent = count; localStorage.setItem('count', count); };
    update();

    document.getElementById('inc').addEventListener('click', () => { count++; update(); });
    document.getElementById('dec').addEventListener('click', () => { count--; update(); });
    document.getElementById('reset').addEventListener('click', () => { count = 0; update(); });

    // Dynamic list
    const listEl  = document.getElementById('list');
    const input   = document.getElementById('newItem');
    const items   = JSON.parse(localStorage.getItem('items') || '[]');

    const renderList = () => {
      listEl.innerHTML = '';
      items.forEach((item, i) => {
        const card = document.createElement('div');
        card.className = 'card';
        card.innerHTML = `<span>\${item}</span>
          <button onclick="items.splice(\${i},1);saveAndRender()">Remove</button>`;
        card.addEventListener('click', () => card.classList.toggle('highlight'));
        listEl.appendChild(card);
      });
    };
    const saveAndRender = () => {
      localStorage.setItem('items', JSON.stringify(items));
      renderList();
    };
    document.getElementById('add').addEventListener('click', () => {
      if (input.value.trim()) { items.push(input.value.trim()); input.value = ''; saveAndRender(); }
    });
    renderList();
  </script>
</body>
</html>

← Promises & Async  |  🏠 Index  |  Node.js →