Frontend engineering is browser engineering. This guide takes you deep into the APIs that power every web feature: DOM traversal, HTML serialization, CSS selector generation, storage layers, cross-tab communication, client-side routing, and analytics SDKs — with 9 interactive problems to lock in the knowledge.
HTML SerializationCSS SelectorslocalStorageCookiesCross-TabRouterAnalytics SDK9 Problems
Why Browser & DOM Skills Matter
Frontend engineering is browser engineering. Every user interaction — a click, a navigation, a form submission — is a browser event. Every feature you build eventually touches the DOM, the storage layer, or a browser API.
Browser and DOM problems appear constantly in frontend system design interviews. Interviewers ask: “Build a client-side router.” “Implement localStorage with TTL.” “Build an analytics SDK.” These are not trick questions — they test whether you understand the platform you build on.
DOM TreeDOM tree: document root branches into html, which branches into head and body, body branches into div and p elements
The DOM tree as a data structure
The DOM is a tree. Every technique in this article — serialization, selector generation, event delegation, analytics click-tracking — relies on recursive tree traversal. Understanding the DOM tree is the prerequisite for all of it.
example.js
// Recursive DOM walk — foundation of all DOM algorithms
function walkDOM(node, visitor) {
visitor(node);
for (const child of node.childNodes) {
walkDOM(child, visitor);
}
}
// Count all elements
let count = 0;
walkDOM(document.body, node => {
if (node.nodeType === Node.ELEMENT_NODE) count++;
});
// Collect all text
const texts = [];
walkDOM(document.body, node => {
if (node.nodeType === Node.TEXT_NODE) texts.push(node.textContent);
});
Key Insight
The DOM tree traversal pattern shows up in HTML serializers, CSS selector generators, scrapers, and test utilities. Master it once and every DOM problem becomes a variation.
1. HTML Serialization
HTML serialization converts between JavaScript data structures and HTML strings or DOM nodes. It has two directions: JSON → HTML (rendering a virtual DOM description) and DOM → JSON (scraping or serializing existing elements).
JSON → HTML: recursive tree builder
Each object in the JSON tree maps to an element: a tag, optional attrs, and optional children. Strings are text nodes.
Editable example loads when this section enters view.
2. DOM Querying & CSS Selector Generation
querySelector and querySelectorAll are the workhorses of DOM querying. But the inverse — generating a unique CSS selector path for any element — is the more interesting interview problem.
querySelector basics
example.js
// Single element — first match
document.querySelector(".nav-link.active");
document.querySelector("#main > article:first-child");
// All matches — returns NodeList
document.querySelectorAll("[data-testid]");
document.querySelectorAll("input[type='checkbox']:checked");
// Scoped to a subtree
const form = document.querySelector("form");
form.querySelectorAll("input, select, textarea");
CSS selector path generation
Given any DOM element, generate the minimal unique CSS selector path from the root. Walk up the ancestor chain building selector parts; stop as soon as an ID is found (IDs are unique by spec).
example.js
function getSelector(el) {
if (el.id) return `#${el.id}`;
const parts = [];
let current = el;
while (current && current !== document.documentElement) {
let selector = current.tagName.toLowerCase();
if (current.id) { parts.unshift(`#${current.id}`); break; }
// nth-of-type for disambiguation among siblings
const siblings = [...current.parentElement.children]
.filter(s => s.tagName === current.tagName);
if (siblings.length > 1) {
const idx = siblings.indexOf(current) + 1;
selector += `:nth-of-type(${idx})`;
}
parts.unshift(selector);
current = current.parentElement;
}
return parts.join(" > ");
}
// Example: body > div:nth-of-type(2) > p > span
Tip
Class names are not always stable — they change with CSS-in-JS tools, obfuscation, and framework updates. An ID or structural path is more reliable for automation and testing. For human-readable selectors, prefer class names over positional selectors.
Form value aggregation
A common real-world task: collect all form inputs into a plain object. Handle checkboxes (boolean), radio buttons (last checked wins), multi-select (array), and all other inputs (string value).
example.js
function serializeForm(form) {
const result = {};
for (const el of form.elements) {
if (!el.name || el.disabled) continue;
if (el.type === "checkbox") {
result[el.name] = el.checked;
} else if (el.type === "radio") {
if (el.checked) result[el.name] = el.value;
} else if (el.tagName === "SELECT" && el.multiple) {
result[el.name] = [...el.selectedOptions].map(o => o.value);
} else {
result[el.name] = el.value;
}
}
return result;
}
PROBLEMCSS Selector Generator
Generate a unique CSS selector path for any DOM element — build the minimal path from root to element.
Editable example loads when this section enters view.
3. Storage — localStorage & Cookies
Storage LayersBrowser storage layers: sessionStorage, localStorage, Cookies, IndexedDB with their properties
Cookie Vs Local StorageStorage comparison table: sessionStorage vs localStorage vs Cookie across scope, persistence, size, JS access, HTTP, HTTPS, and CSRF protection
localStorage fundamentals
localStorage is synchronous, has a ~5 MB limit, stores only strings (use JSON.stringify/JSON.parse), and is shared across all tabs on the same origin.
localStorage has no built-in expiry. The common pattern: wrap every value in an envelope that stores the expiry timestamp. On read, check whether the item has expired and delete it if so.
Cookies have a notoriously awkward API: document.cookie is a single string that concatenates all cookies. Reading requires parsing; writing sets or updates one cookie at a time.
example.js
// Set cookie with expiry, path, SameSite
function setCookie(name, value, { days, path = "/", sameSite = "Lax" } = {}) {
let cookie = `${encodeURIComponent(name)}=${encodeURIComponent(value)}`;
if (days) {
const expires = new Date(Date.now() + days * 864e5).toUTCString();
cookie += `; expires=${expires}`;
}
cookie += `; path=${path}; SameSite=${sameSite}`;
document.cookie = cookie;
}
// Get cookie by name
function getCookie(name) {
const key = encodeURIComponent(name) + "=";
const pair = document.cookie
.split("; ")
.find(c => c.startsWith(key));
return pair ? decodeURIComponent(pair.slice(key.length)) : null;
}
// Delete cookie — set expiry in the past
function deleteCookie(name, path = "/") {
document.cookie = `${encodeURIComponent(name)}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=${path}`;
}
Note
Cookies are the only storage mechanism sent automatically with every HTTP request. This makes them the right choice for authentication tokens — but also means their size matters. Keep auth cookies small. Use HttpOnly and Secure flags on auth cookies (server-set only).
PROBLEMlocalStorage with TTL
Extend localStorage to support automatic key expiry — set TTL per key, auto-delete on access after expiry.
Editable example loads when this section enters view.
4. Cross-Tab Communication
Cross TabCross-tab communication: Tab A sends via BroadcastChannel to Tab B, with localStorage storage event as alternative
BroadcastChannel API
BroadcastChannel lets all tabs, windows, and workers on the same origin communicate directly. Create a channel with a name; any tab listening on that name receives the message. The sending tab does not receive its own messages.
example.js
// Tab A — sender
const channel = new BroadcastChannel("app-state");
channel.postMessage({ type: "THEME_CHANGED", theme: "dark" });
// Tab B — receiver
const channel = new BroadcastChannel("app-state");
channel.onmessage = (event) => {
const { type, theme } = event.data;
if (type === "THEME_CHANGED") applyTheme(theme);
};
// Clean up when done
channel.close();
localStorage storage event
The older alternative: listen for storage events on window. These fire in every tab except the one that made the change — the same semantics as BroadcastChannel.
example.js
// In Tab B — listens for localStorage changes from other tabs
window.addEventListener("storage", (event) => {
if (event.key === "theme") {
applyTheme(event.newValue);
}
});
// In Tab A — triggers the storage event in Tab B
localStorage.setItem("theme", "dark");
Tip
Prefer BroadcastChannel for new code — it supports arbitrary objects (not just strings), has an explicit channel name, and is designed specifically for this use case. The storage event is a side effect of localStorage, not a messaging API.
Use cases
Logout all tabs — when the user logs out in one tab, broadcast a LOGOUT event and redirect all others.
Theme / preferences sync — changes made in a settings panel propagate to all open tabs instantly.
Cart / auth state — add an item to cart in one tab, see it update in another without a page refresh.
Leader election — tabs coordinate to elect a single leader to own background tasks (polling, WebSocket).
PROBLEMCross-Tab Data Sharing
Implement real-time cross-tab data sharing using BroadcastChannel — sync state across browser tabs on the same origin.
Editable example loads when this section enters view.
5. Client-Side Routing
RouterClient-side routing: history.pushState changes the URL, the application dispatches a render, and popstate only fires for back/forward traversal
History API
Client-side routing is built on two primitives: history.pushState() to update the URL without a page load, and the popstate event to detect browser back/forward navigation.
example.js
// Navigate to /dashboard — updates URL bar, no page load
history.pushState({ page: "dashboard" }, "", "/dashboard");
// Replace current history entry (no new entry)
history.replaceState(null, "", "/dashboard?tab=settings");
// Detect back/forward navigation
window.addEventListener("popstate", (event) => {
renderRoute(location.pathname);
});
// Link intercept — prevent full reload, use pushState
document.addEventListener("click", (e) => {
const link = e.target.closest("a[href]");
if (!link) return;
const url = new URL(link.href);
if (url.origin !== location.origin) return; // external link
e.preventDefault();
history.pushState(null, "", url.pathname);
renderRoute(url.pathname);
});
Router with dynamic params
Route matching converts URL patterns like /user/:id into regular expressions, extracting named parameters from the actual URL path.
Hash routing uses location.hash and the hashchange event. Since hash changes never trigger a server request, this approach works on any static file host with no server configuration.
History API is preferred for production SPAs — URLs look clean and work with SSR. Hash routing is simpler and works without any server configuration, making it useful for demos, prototypes, and tools deployed on static hosts.
Nested routing
Real apps have nested layouts: a dashboard with a sidebar that persists across/dashboard/analytics and /dashboard/settings. Nested routing means matching both the layout route and the child route.
example.js
// Route config with nesting
const routes = [
{
path: "/dashboard",
layout: DashboardLayout,
children: [
{ path: "/dashboard/analytics", component: AnalyticsPage },
{ path: "/dashboard/settings", component: SettingsPage },
{ path: "/dashboard/users", component: UsersPage },
],
},
{ path: "/", component: HomePage },
];
function matchNested(path) {
for (const route of routes) {
if (route.children) {
for (const child of route.children) {
if (path.startsWith(child.path)) {
return { layout: route.layout, page: child.component };
}
}
} else if (route.path === path) {
return { page: route.component };
}
}
return null;
}
// Render with layout wrapping
const match = matchNested(location.pathname);
if (match) {
const content = match.page ? React.createElement(match.page) : null;
if (match.layout) {
// Wrap in layout component (sidebar, header, etc.)
React.createElement(match.layout, null, content);
}
}
Route guards
Route guards protect pages behind authentication, feature flags, or role checks. Implement them as a middleware layer that runs before the route handler.
example.js
class GuardedRouter extends Router {
#guards = [];
guard(fn) {
this.#guards.push(fn);
return this;
}
#match(pattern, path) {
const keys = [];
const regex = new RegExp(
"^" + pattern.replace(/:([^/]+)/g, (_, k) => {
keys.push(k);
return "([^/]+)";
}) + "$"
);
const result = regex.exec(path);
if (!result) return null;
return Object.fromEntries(keys.map((k, i) => [k, result[i + 1]]));
}
#dispatch(path) {
// Run all guards before matching routes
for (const guard of this.#guards) {
const result = guard(path);
if (result === false) return; // block
if (typeof result === "string") {
// redirect
history.pushState(null, "", result);
this.#renderRoute(result);
return;
}
}
for (const [pattern, handler] of this.#routes) {
const match = this.#match(pattern, path);
if (match) { handler(match); return; }
}
}
#renderRoute(path) {
for (const [pattern, handler] of this.#routes) {
const match = this.#match(pattern, path);
if (match) { handler(match); return; }
}
}
}
// Usage
const router = new GuardedRouter();
// Auth guard — redirect to /login if not authenticated
router.guard((path) => {
const isAuthenticated = !!sessionStorage.getItem("token");
const isPublic = ["/", "/login", "/signup"].includes(path);
if (!isAuthenticated && !isPublic) return "/login";
return true; // allow
});
// Feature flag guard
router.guard((path) => {
if (path.startsWith("/beta") && !localStorage.getItem("beta_access")) {
return false; // silently block
}
return true;
});
Tip
Route guards form a pipeline — each guard can allow, block, or redirect. Keep guards pure (no side effects) and order them from cheapest to most expensive (auth check before role check).
PROBLEMClient-Side Router
Implement a client-side Express-style router with route matching, dynamic params, and middleware support.
Editable example loads when this section enters view.
6. Analytics SDK
An analytics SDK must be lightweight, non-blocking, and reliable — events must reach the server even when the user closes the page. The key techniques: event batching, the Beacon API for fire-and-forget delivery, and session management.
navigator.sendBeacon(url, data) sends data asynchronously in a way that does not block page unload. Unlike fetch, the browser guarantees delivery even if the page is being closed.
example.js
// fetch — may be cancelled if page unloads
fetch("/api/events", { method: "POST", body: JSON.stringify(events) });
// sendBeacon — survives page unload, fire-and-forget
navigator.sendBeacon("/api/events", JSON.stringify(events));
// Returns true if the request was queued, false if it failed
Warning
sendBeacon has no response — you cannot read the server reply. Use it only for data you send but do not need a response to. The payload must be Blob, ArrayBuffer, FormData, or URLSearchParams — for JSON, use new Blob([json], { type: "application/json" }).
Auto-tracking: event delegation
Instead of adding individual listeners to every button, attach a single listener to document and let events bubble up. This works for dynamically added elements and has near-zero setup cost.
example.js
// Single listener handles all current + future buttons
document.addEventListener("click", (event) => {
const el = event.target.closest("[data-track]");
if (!el) return;
analytics.track("click", {
trackId: el.dataset.track,
text: el.textContent?.trim().slice(0, 100),
tag: el.tagName.toLowerCase(),
});
});
// In HTML:
// <button data-track="signup-cta">Sign up</button>
// <a data-track="nav-pricing" href="/pricing">Pricing</a>
Event DelegationEvent delegation: without delegation 1000 individual listeners; with delegation one listener on parent captures all events via bubbling
Session tracking
Generate a unique session ID on first visit, persist in sessionStorage, and attach to every event. This lets you group events by session for funnel analysis.
example.js
// Session ID — survives page reloads but not tab close
const SESSION_KEY = "__session_id";
function getSessionId() {
let id = sessionStorage.getItem(SESSION_KEY);
if (!id) {
id = crypto.randomUUID();
sessionStorage.setItem(SESSION_KEY, id);
}
return id;
}
// Track page view with session context
analytics.track("page_view", {
path: location.pathname,
referrer: document.referrer || null,
sessionId: getSessionId(),
});
Page timing (performance.timing)
The Performance API gives you precise timing data: DNS lookup, TCP connect, TTFB, DOM content loaded, and more. Track these as a single batch event after the page finishes loading.
example.js
function trackPageTiming() {
// Wait for the load event to ensure full timing data
window.addEventListener("load", () => {
// Use requestAnimationFrame to defer after paint
requestAnimationFrame(() => {
setTimeout(() => {
const perf = performance.timing;
analytics.track("page_timing", {
dns: perf.domainLookupEnd - perf.domainLookupStart,
tcp: perf.connectEnd - perf.connectStart,
ttfb: perf.responseStart - perf.requestStart,
domContentLoaded: perf.domContentLoadedEventEnd - perf.navigationStart,
load: perf.loadEventEnd - perf.navigationStart,
resourceCount: performance.getEntriesByType("resource").length,
});
}, 0);
});
});
}
trackPageTiming();
// Track Core Web Vitals via PerformanceObserver
if ("PerformanceObserver" in window) {
new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
if (entry.entryType === "largest-contentful-paint") {
analytics.track("lcp", { value: entry.startTime });
}
}
}).observe({ type: "largest-contentful-paint", buffered: true });
}
Note
Always defer performance tracking after the load event. The performance.timing API provides navigation timing; use PerformanceObserver for Core Web Vitals (LCP, CLS, FID/INP).
Error tracking
JavaScript errors crash silently. Catch unhandled exceptions and promise rejections to understand what broke in production. Include stack traces, URL, and user agent.
Stack traces can be large. Truncate to the first 500 characters before sending. Be careful not to send sensitive data (auth tokens, user PII) in error payloads. Consider using source maps on the server to deobfuscate minified stacks.
PROBLEMAnalytics SDK
Build a lightweight client-side analytics SDK — track events, batch them, flush on page unload using sendBeacon.
Editable example loads when this section enters view.
DOM Performance Patterns
DOM operations are among the most expensive operations in the browser. Every read, write, and layout access has a cost. Understanding the rendering pipeline — reflow, repaint, compositing — is essential for building performant web apps.
Reflow vs Repaint
Reflow (layout) recalculates the position and size of elements. It is triggered when you change geometry — width, height, margins, padding, font-size, or when you read layout properties like offsetHeight or scrollTop. Reflow is expensive because the browser must re-compute the layout tree.
Repaint redraws pixels to the screen without recalculating layout. It is triggered by visual changes — color, background, visibility, box-shadow. Repaint is cheaper than reflow but still costly at scale.
Every DOM insertion (appendChild, insertBefore) triggers a reflow. To insert many nodes, build the subtree in a DocumentFragment (off-screen container) and append it once.
example.js
// ❌ Bad: one reflow per insertion
const list = document.getElementById("list");
for (const item of items) {
const li = document.createElement("li");
li.textContent = item;
list.appendChild(li); // reflow every time
}
// ✅ Good: fragment batches all insertions
const fragment = document.createDocumentFragment();
for (const item of items) {
const li = document.createElement("li");
li.textContent = item;
fragment.appendChild(li);
}
list.appendChild(fragment); // single reflow
// Modern alternative: innerHTML with string join
const html = items.map(i => `<li>${escapeHTML(i)}</li>`).join("");
list.innerHTML = html; // one reflow (but unsafe with user data!)
requestAnimationFrame — 60fps visual updates
requestAnimationFrame (rAF) schedules a function to run before the next paint cycle — approximately every 16ms at 60fps. Use it for animations, DOM reads, and any visual update that must be smooth.
example.js
// Smooth animation loop
function animate(element) {
let position = 0;
let startTime = null;
function step(timestamp) {
if (!startTime) startTime = timestamp;
const elapsed = timestamp - startTime;
// Move 200px over 1 second
position = Math.min((elapsed / 1000) * 200, 200);
element.style.transform = `translateX(${position}px)`;
if (position < 200) {
requestAnimationFrame(step); // schedule next frame
}
}
requestAnimationFrame(step);
}
// rAF + read/write batching pattern
function batchDOMUpdates(reads, writes) {
requestAnimationFrame(() => {
const values = reads.map(fn => fn()); // batch all reads
writes.forEach((fn, i) => fn(values[i])); // batch all writes
});
}
// Usage: read heights, set equal heights
batchDOMUpdates(
[() => box1.offsetHeight, () => box2.offsetHeight],
[(h) => { box1.style.height = Math.max(h, box2.offsetHeight) + "px"; },
(h) => { box2.style.height = Math.max(box1.offsetHeight, h) + "px"; }]
);
Note
setTimeout(fn, 0) vs requestAnimationFrame(fn): setTimeout runs after the minimum timeout, which could miss a frame. rAF runs right before the browser paints, so your changes are rendered in the current frame. Always prefer rAF for visual updates.
IntersectionObserver fires a callback when a target element enters or leaves the viewport (or a root element). It is far more efficient than scroll-event listeners for detecting visibility.
example.js
// Lazy load images
const lazyObserver = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src; // swap data-src → src
img.removeAttribute("data-src");
lazyObserver.unobserve(img); // stop observing once loaded
}
});
}, {
rootMargin: "200px", // start loading 200px before viewport
threshold: 0.01, // fire when 1% visible
});
document.querySelectorAll("img[data-src]").forEach(img => {
lazyObserver.observe(img);
});
// Infinite scroll
const sentinelObserver = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting) {
loadMoreItems(); // fetch next page
}
}, { threshold: 1.0 });
const sentinel = document.getElementById("scroll-sentinel");
sentinelObserver.observe(sentinel);
// Tab visibility — pause animations when tab is hidden
document.addEventListener("visibilitychange", () => {
if (document.hidden) {
pauseAnimations();
} else {
resumeAnimations();
}
});
Tip
Use rootMargin to trigger loads early (before the user scrolls to the element). A value of "200px" means "load when the element is 200px outside the viewport" — creating a seamless experience.
Virtual DOMVirtual DOM cycle: current vDOM compared against next vDOM, diff produces patches, only changed nodes applied to real DOM
Interview Cheat Sheet
These eight questions cover the core concepts that interviewers probe when they ask about browser APIs, DOM manipulation, and frontend system design.
1How do you generate a unique CSS selector for a DOM element?
Walk up the ancestor chain from the target element. For each node, use tagName.toLowerCase(). If the element has siblings of the same tag, append :nth-of-type(n). Stop and prefix with #id when an ancestor with an ID is found. Join parts with ' > '.
2How does localStorage differ from sessionStorage and cookies?
localStorage persists indefinitely and is shared across all tabs of the same origin. sessionStorage is cleared when the tab closes and is isolated per tab. Cookies have configurable expiry, are sent with every HTTP request, and can be set HttpOnly/Secure — the only mechanism the server can read.
3How do you implement localStorage with TTL?
Wrap each stored value in an envelope: { value, expiry: Date.now() + ttlMs }. On every get(), check if Date.now() > expiry — if so, call removeItem and return null. The TTL check only fires on read; you can add a periodic sweeper for proactive cleanup.
4How does BroadcastChannel differ from localStorage storage events?
BroadcastChannel is a dedicated messaging API — postMessage sends to all tabs on the same channel name, and it accepts any serializable object. localStorage storage events fire as a side effect of writing to localStorage, carry the old/new value as strings, and also fire only in other tabs. BroadcastChannel is cleaner and more intentional.
5How does client-side routing work (History API)?
history.pushState(state, title, url) updates the URL bar without a server request. The popstate event fires on back/forward navigation. The router listens to popstate and re-dispatches to match the new pathname. For link clicks, intercept with event.preventDefault(), call pushState, then dispatch manually.
6What is navigator.sendBeacon and why use it for analytics?
sendBeacon sends a small HTTP POST asynchronously, guaranteed to complete even if the page is being closed — unlike fetch which can be cancelled on unload. It is fire-and-forget (no response). Use it in beforeunload and visibilitychange handlers to reliably flush event queues.
7How do you prevent XSS in HTML serialization?
Escape all five special characters before inserting user content into HTML: & → &, < → <, > → >, " → ", ' → '. Alternatively, use DOM APIs — textContent for text, setAttribute for attributes — which escape automatically. Never use innerHTML = userInput.
8What is event delegation and why is it used in analytics tracking?
Event delegation attaches a single listener high in the tree (e.g., document) instead of on each individual element. Events bubble up, so the single listener catches them all. For analytics, this means dynamically added elements are tracked automatically with zero setup per element, and the memory cost is one listener regardless of how many buttons exist.
Key Takeaways
1.The DOM is a tree. Every DOM algorithm — serialization, selector generation, click tracking — is fundamentally a recursive tree traversal.
2.HTML serialization requires HTML escaping for all user-supplied text. The five characters to escape: &, <, >, ", '. Skipping this is an XSS vulnerability.
3.CSS selector generation walks up the ancestor chain. Stop at an ID (unique by spec); use :nth-of-type to disambiguate siblings of the same tag.
4.localStorage has no built-in expiry. Implement TTL by storing an expiry timestamp alongside the value and checking it on every read.
5.Cookies are the only storage mechanism sent with HTTP requests — making them right for auth tokens. Prefer HttpOnly + Secure flags for sensitive cookies.
6.BroadcastChannel is the modern API for cross-tab communication. The storage event is the older alternative — it fires as a side effect of localStorage writes, not as an intentional message.
7.Client-side routing is built on history.pushState (silent URL updates) and the popstate event (back/forward detection). Intercept link clicks to prevent full page reloads.
8.navigator.sendBeacon guarantees event delivery on page unload — unlike fetch which can be cancelled. Use it in beforeunload and visibilitychange to flush analytics queues.
9.Event delegation attaches one listener at the document level instead of one per element. This covers dynamic elements automatically and is the standard approach for click-tracking in analytics SDKs.
10.Batch analytics events before sending. Sending one HTTP request per event is wasteful. Queue locally, flush at a batch size threshold, and always flush on page close.