Browser JavaScript
Browser JavaScript & DOM Manipulation
Learn how to use JavaScript in web browsers to create interactive web pages.
What You’ll Learn
This section covers browser-specific JavaScript APIs and techniques:
- The DOM: Understanding the Document Object Model
- Selectors: Finding elements in the page
- DOM Manipulation: Reading and modifying page content
- Events: Responding to user interactions
- Browser APIs: Fetch, localStorage, and more
Prerequisites
Complete the JavaScript fundamentals section first, especially:
- Variables and data types
- Functions
- Objects and arrays
Learning Path
Follow the lessons sequentially to build a solid foundation in browser-based JavaScript development.
What is the DOM? The DOM is short acronym for “Document Object Model”. This is basically everything you see in the web browser. You write HTML that gets transformed by the browser into the DOM. You write javaScript that changes parts of the DOM.
With some very simple and quick coding you’ll be able to enhance HTML documents greatly. In the past the majority of people used jQuery library to interact with the DOM.
How to select elements of the DOM. I’ll start out by saying that I am introducing javaScript selectors to you long before most javaScript tutorials do and that I am purposely doing this before even basic javaScript logic because for one: in my experience this is the fist place that newbies interact with existing code, and second: it is something that many veterans don’t really know if they mostly interacted with the DOM by way of jQuery.
Reading from elements of the DOM we have selected. After selecting a piece of the DOM you probably want to do something with it. Before we can do that we have to decide what piece of the DOM element we want to work with.
select an element like this:
let mySelection = document.getElementByID("someID"); then you can interact with it like so:
let someHtml = mySelection.innerHTML; selects the html inside the chosen element: .
Working with NodeLists In my daily working with NodeLists I find I normally just want to convert them into arrays so mainly I just use the ES6 spread operator (see below) to convert it into something I can use.
Using Array.from(): Array.from(mySelection).forEach(doSomethingWithEachElement)
Using the ES6 spread operator (…) : let myArray = [...nodeList] i guess this may not work in some browsers? still testing to confirm.
Next Article: Event Listeners
Event Listeners are how you enable an element to respond to different events. By default events bubble down the DOM tree so that a single action can trigger multiple events.
Event Listeners add event listener: mySelection.addEventListener('click', foo); Common Event Listeners onload – when the page loads onclick – when a user clicks something onmouseover – when a user mouses over something onfocus – when a user puts the cursor in a form field onblur – When a user leaves a form field Next Article: Variables
The Fetch API provides a modern way to make HTTP requests in the browser. It replaces the older XMLHttpRequest with a cleaner, promise-based interface.
Basic GET Request // Simple fetch fetch('https://api.example.com/users') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error)); With async/await (cleaner):
async function getUsers() { try { const response = await fetch('https://api.example.com/users'); const data = await response.json(); console.log(data); } catch (error) { console.error('Error:', error); } } getUsers(); Understanding the Response async function checkResponse() { const response = await fetch('https://api.
Web Storage provides two mechanisms for storing data in the browser: localStorage and sessionStorage. Both offer simple key-value storage without needing a database or server.
localStorage vs sessionStorage Feature localStorage sessionStorage Lifespan Persists forever Until tab closes Scope Shared across all tabs One tab only Capacity ~5-10 MB ~5-10 MB Use case User preferences Temporary session data localStorage Basics // Store data localStorage.setItem('username', 'Alice'); localStorage.setItem('theme', 'dark'); // Retrieve data const username = localStorage.
Creating and modifying DOM elements dynamically is essential for building interactive web applications. Let’s explore the powerful techniques for manipulating the Document Object Model.
Creating Elements createElement() Create new HTML elements:
// Create a new div element const div = document.createElement('div'); // Create other elements const paragraph = document.createElement('p'); const button = document.createElement('button'); const link = document.createElement('a'); const image = document.createElement('img'); Adding Content const heading = document.createElement('h2'); // Set text content (safe - escapes HTML) heading.
Understanding how to work with element attributes, classes, and styles is crucial for creating dynamic web pages. Let’s explore the powerful methods JavaScript provides.
HTML Attributes vs DOM Properties Important distinction:
<input type="text" value="default" id="myInput"> const input = document.querySelector('#myInput'); // Attribute (in HTML): Initial value console.log(input.getAttribute('value')); // "default" // Property (in DOM): Current value console.log(input.value); // "default" (initially) // User types "hello" console.log(input.getAttribute('value')); // Still "default" console.log(input.value); // "hello" (current value) Key difference:
DOM traversal is navigating the document tree to find elements relative to other elements. Instead of searching the entire document, traverse from known elements to their relatives.
The DOM Tree Structure HTML creates a tree of nodes:
<div id="container"> <h2>Title</h2> <p>First paragraph</p> <p>Second paragraph</p> </div> container (div) ├── h2 (Title) ├── p (First paragraph) └── p (Second paragraph) Parent Elements parentElement Get the parent element:
const paragraph = document.querySelector('p'); // Get parent const parent = paragraph.
Beyond basic event listeners, understanding event propagation, delegation, and advanced patterns will make your code more efficient and maintainable.
Event Propagation Events propagate through the DOM in three phases:
1. Capture phase: From document → target 2. Target phase: At the target element 3. Bubble phase: From target → document Event Bubbling Events bubble up from child to parent:
<div id="outer"> <div id="middle"> <button id="inner">Click me</button> </div> </div> const outer = document.
Client-side validation improves user experience by providing immediate feedback before form submission. Let’s explore both HTML5 validation and custom JavaScript validation.
HTML5 Validation Modern browsers provide built-in validation:
Required Fields <form> <input type="text" name="username" required> <input type="email" name="email" required> <button type="submit">Submit</button> </form> Browser automatically shows error if empty when submitted.
Input Types Different input types have automatic validation:
<!-- Email validation --> <input type="email" name="email" required> <!-- URL validation --> <input type="url" name="website"> <!
The FormData API provides an easy way to construct form data for sending with AJAX requests, especially useful for file uploads and complex forms.
Creating FormData From a Form Element <form id="myForm"> <input type="text" name="username" value="alice"> <input type="email" name="email" value="alice@example.com"> <input type="number" name="age" value="25"> <button type="submit">Submit</button> </form> const form = document.querySelector('#myForm'); form.addEventListener('submit', (e) => { e.preventDefault(); // Create FormData from form const formData = new FormData(form); // Log all entries for (let [key, value] of formData.
Storage Options Overview Modern browsers offer multiple storage APIs:
Storage Type Capacity Persistence Use Case localStorage ~5-10 MB Forever User preferences, settings sessionStorage ~5-10 MB Tab session Temporary form data IndexedDB 50+ MB Forever Large datasets, offline apps Cookies 4 KB Configurable Authentication tokens sessionStorage Advanced Patterns Multi-Step Form State Preserve form data across page navigations within same tab:
// Save form state on every change function saveFormState() { const formData = { step: currentStep, personalInfo: { name: document.
What is the Geolocation API? The Geolocation API allows you to access the user’s geographic location (with their permission). Perfect for maps, location-based services, and local recommendations.
if ('geolocation' in navigator) { navigator.geolocation.getCurrentPosition((position) => { console.log('Latitude:', position.coords.latitude); console.log('Longitude:', position.coords.longitude); }); } Important: Requires HTTPS (except localhost) and user permission.
Checking for Support function supportsGeolocation() { return 'geolocation' in navigator; } if (supportsGeolocation()) { console.log('Geolocation is supported'); } else { console.log('Geolocation is not supported'); // Show fallback UI } Getting Current Position Basic Usage function getLocation() { if ('geolocation' in navigator) { navigator.
What are Browser Notifications? The Notifications API allows you to display system notifications outside the browser window, even when the page isn’t visible. Perfect for chat apps, reminders, and real-time updates.
if ('Notification' in window) { Notification.requestPermission().then(permission => { if (permission === 'granted') { new Notification('Hello!', { body: 'This is a browser notification', icon: '/icon.png' }); } }); } Requirements:
HTTPS (or localhost) User permission Service Worker (for background notifications) Checking for Support function supportsNotifications() { return 'Notification' in window; } if (supportsNotifications()) { console.