Skip to content
JavaScript DOM & Browser APIs Explained — Complete Web Manipulation Guide

JavaScript DOM & Browser APIs Explained — Complete Web Manipulation Guide

DodaTech Updated Jun 6, 2026 8 min read

The Document Object Model (DOM) is JavaScript’s bridge to HTML — it lets you read, create, modify, and delete any element on a web page after the page has loaded.

What You’ll Learn

  • Selecting elements with querySelector, getElementById, and more
  • Changing content, attributes, and CSS styles
  • Creating, inserting, and removing elements
  • Handling events with addEventListener and event delegation
  • Using the Window object, Storage, Cookies, and Web APIs
  • Building an interactive mini project

Why the DOM Matters

The DOM is what makes web pages dynamic. Without it, JavaScript can compute numbers but can’t change what you see on screen. The Doda Browser uses DOM manipulation to render tabs, display bookmarks, and show download progress. The Durga Antivirus Pro dashboard updates threat statistics and scan status in real time by manipulating the DOM. Every interactive website you’ve ever used relies on DOM manipulation.

Learning Path

    flowchart LR
  A[JavaScript Basics] --> B[Functions]
  B --> C[DOM & Browser APIs]
  C --> D[Async JS]
  C --> E[JSON]
  C --> F[You Are Here]
  
Prerequisites: You should understand HTML (elements, attributes, structure) and JavaScript (variables, functions, events).

What Is the DOM?

When a browser loads an HTML page, it creates a tree of objects called the Document Object Model. Each HTML element becomes a “node” in this tree. JavaScript can navigate this tree, find elements, and change them.

Think of the DOM like a family tree. The <html> element is the grandparent. <body> is its child. And each <div>, <p>, or <button> is a descendant. JavaScript is the family archivist who can add, remove, or rename anyone in the tree.

    flowchart TD
  A[document] --> B[html]
  B --> C[head]
  B --> D[body]
  D --> E[header]
  D --> F[main]
  D --> G[footer]
  E --> H[h1]
  F --> I[p]
  F --> J[button]
  

Selecting Elements

Before you can change an element, you need to find it:

// Single element — returns the first match or null
const header = document.getElementById('header');
const firstBtn = document.querySelector('.btn');     // CSS selector
const nav = document.querySelector('nav');           // Tag selector

// Multiple elements — returns NodeList or HTMLCollection
const buttons = document.querySelectorAll('.btn');   // Static NodeList
const items = document.getElementsByClassName('item'); // Live HTMLCollection
const divs = document.getElementsByTagName('div');   // Live HTMLCollection

querySelector vs getElementById: Use querySelector for flexibility (any CSS selector) and getElementById for raw speed when you know the ID.

Changing Content & Attributes

const el = document.querySelector('#output');

// Text content (safe — no HTML parsing, prevents XSS)
el.textContent = 'Hello World';

// HTML content (dangerous with user input)
el.innerHTML = '<strong>Hello World</strong>';

// Attributes
el.setAttribute('data-id', '123');
console.log(el.getAttribute('data-id'));   // '123'
console.log(el.hasAttribute('data-id'));   // true
el.removeAttribute('data-id');

// Classes
el.classList.add('active');
el.classList.remove('hidden');
el.classList.toggle('visible');
console.log(el.classList.contains('active')); // true

Security warning: Never use innerHTML with user input (like form fields or URL parameters). This creates XSS (Cross-Site Scripting) vulnerabilities. Use textContent for text, or sanitize HTML first.

Changing CSS

const el = document.querySelector('#box');

el.style.color = '#3498db';              // camelCase property names
el.style.backgroundColor = '#f0f0f0';    // background-color → backgroundColor
el.style.fontSize = '18px';              // font-size → fontSize
el.style.display = 'none';               // hide element

// CSS custom properties
el.style.setProperty('--primary', '#3498db');

Anticipating confusion: CSS properties like background-color become backgroundColor in JavaScript (camelCase). The hyphen is removed and the next letter is capitalized.

Creating & Removing Elements

const list = document.querySelector('#list');

// Create a new element
const item = document.createElement('li');
item.textContent = 'New item';
item.classList.add('list-item');

// Insert into DOM
list.appendChild(item);          // at end
list.prepend(item);              // at start
list.insertBefore(item, list.firstChild);  // before first child

// Remove
item.remove();
// or: list.removeChild(item);

// Clone
const clone = item.cloneNode(true);  // true = deep clone (includes children)

Why creating elements matters: Creating elements dynamically lets you build UI from data. For example, the Durga Antivirus Pro dashboard creates a new threat card for each detected virus by iterating over an array of threats and calling document.createElement('div') for each one.

Events

Events are how JavaScript responds to user actions — clicks, key presses, form submissions:

const btn = document.querySelector('#btn');

btn.addEventListener('click', (event) => {
  console.log('Button clicked!');
  console.log('Target:', event.target);     // The element clicked
  console.log('Current target:', event.currentTarget);  // Element listener attached to
});

Event Object Properties

element.addEventListener('click', (e) => {
  e.target;             // The element that triggered the event
  e.currentTarget;      // The element the listener is on
  e.preventDefault();   // Stop browser default (e.g., link navigation, form submit)
  e.stopPropagation();  // Stop event from bubbling up
});

Event Delegation

Instead of attaching a listener to every child, attach one to the parent:

document.querySelector('#list').addEventListener('click', (e) => {
  if (e.target.matches('li')) {
    console.log('List item clicked:', e.target.textContent);
  }
});

Why delegation matters: If you have 100 list items, you’d need 100 event listeners. With delegation, you need one. It also works for items added dynamically after the page loads.

Window Object (BOM)

The Browser Object Model gives you access to browser features:

// Window properties
console.log(window.innerWidth);     // Viewport width
console.log(window.innerHeight);    // Viewport height
console.log(window.scrollY);        // Current scroll position
console.log(window.location.href);  // Current URL

// Dialog boxes
alert('Hello');
const confirmed = confirm('Are you sure?');  // true/false
const name = prompt('Enter name:');          // string or null

// Timers
setTimeout(() => console.log('After 1s'), 1000);
const interval = setInterval(() => console.log('Every 1s'), 1000);
clearInterval(interval);  // Stop the interval

Storage

// localStorage — persists after browser close
localStorage.setItem('theme', 'dark');
console.log(localStorage.getItem('theme'));  // 'dark'
localStorage.removeItem('theme');
localStorage.clear();

// sessionStorage — cleared when tab closes
sessionStorage.setItem('temp', 'data');

// Storage only stores strings — use JSON for objects
const user = { name: 'Alice' };
localStorage.setItem('user', JSON.stringify(user));
const parsed = JSON.parse(localStorage.getItem('user'));

Common Mistakes

1. Using innerHTML with user input (XSS)

el.innerHTML = userInput;  // Anyone can inject <script> tags

Fix: Use textContent for text. Sanitize HTML with a library like DOMPurify if you must use innerHTML.

2. DOM queries before the page loads

document.querySelector('#app');  // null — element doesn't exist yet

Fix: Put <script> at the end of <body> or use DOMContentLoaded event.

3. Too many DOM queries in loops

for (let i = 0; i < 1000; i++) {
  document.querySelector('.item');  // Re-queries the DOM every time!
}

Fix: Cache the reference: const item = document.querySelector('.item');

4. Memory leaks from event listeners

Adding many listeners without removing them prevents garbage collection. Use removeEventListener or event delegation.

5. Forgetting await with async operations

const data = fetch('/api/data');  // Returns a Promise, not data!

6. Using innerHTML instead of insertAdjacentHTML

innerHTML replaces ALL content. insertAdjacentHTML inserts without destroying existing content.

Practice Questions

  1. What’s the difference between textContent and innerHTML? textContent sets plain text (safe). innerHTML parses HTML (XSS risk with user input).

  2. What is event delegation? Attaching a single listener to a parent instead of individual listeners on each child. Uses event bubbling.

  3. What’s the difference between localStorage and sessionStorage? localStorage persists until cleared. sessionStorage clears when the tab closes.

  4. How do you prevent a form from submitting? event.preventDefault() in the form’s submit event handler.

Challenge: Build a todo list where users can add items (with an input and button) and delete items (by clicking on them). Store the items in localStorage so they persist after page reload.

FAQ

What is the difference between querySelectorAll and getElementsByClassName?
querySelectorAll returns a static NodeList. getElementsByClassName returns a live HTMLCollection that updates when the DOM changes.
What is event delegation?
Attaching a single event listener to a parent instead of individual listeners on each child. Works because events bubble up.
What is the difference between localStorage and sessionStorage?
localStorage persists until explicitly cleared. sessionStorage is cleared when the tab is closed.
What is DOMContentLoaded vs load?
DOMContentLoaded fires when HTML is parsed. load waits for all resources (images, stylesheets) to finish loading.
How do I prevent a form from submitting?
event.preventDefault() inside the form’s submit event handler.
What is requestAnimationFrame?
A method that schedules code before the next repaint. More efficient than setTimeout for animations.

Try It Yourself

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>DOM Playground</title>
  <style>
    body { font-family: Arial, sans-serif; padding: 2rem; }
    #box { padding: 1rem; margin: 1rem 0; background: #f0f0f0; border-radius: 5px; }
    button { margin-right: 0.5rem; padding: 0.5rem 1rem; }
  </style>
</head>
<body>
  <h1>DOM Manipulation Sandbox</h1>
  <div id="box">This box changes when you click the buttons.</div>
  <button id="btnText">Set Text</button>
  <button id="btnHide">Toggle Hide</button>
  <button id="btnColor">Change Color</button>

  <script>
    const box = document.getElementById('box');

    document.getElementById('btnText').addEventListener('click', () => {
      box.textContent = 'Text updated at ' + new Date().toLocaleTimeString();
    });

    document.getElementById('btnHide').addEventListener('click', () => {
      box.classList.toggle('hidden');
    });

    document.getElementById('btnColor').addEventListener('click', () => {
      const colors = ['#3498db', '#e74c3c', '#2ecc71', '#f39c12'];
      const random = colors[Math.floor(Math.random() * colors.length)];
      box.style.backgroundColor = random;
    });
  </script>
</body>
</html>

What’s Next

Now that you can manipulate the DOM, learn about data and async operations:

LessonDescription
JavaScript HomeBack to the JavaScript hub
https://tutorials.dodatech.com/programming-languages/javascript/js-async/Async JavaScript — fetch data from APIs
https://tutorials.dodatech.com/programming-languages/javascript/js-json/JSON — working with data from servers
https://tutorials.dodatech.com/programming-languages/javascript/js-modules/Modules & Error Handling
CSS AnimationsCombine CSS transitions with DOM manipulation

Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

What’s Next

Congratulations on completing this Js Dom tutorial! Here’s where to go from here:

  • Practice daily — Consistency is more important than long study sessions
  • Build a project — Apply what you learned by building something real
  • Explore related topics — Check out other tutorials in the same category
  • Join the community — Discuss with other learners and share your progress

Remember: every expert was once a beginner. Keep coding!

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro