742 commands · 48 cheat sheets · 6 subcategories
HTML master quick reference — Page 3
Browse 191 commands from 12 focused cheat sheets on page 3 of 4. Each example opens its matching detailed section.
DOM and Lifecycle · 18 commands
Browser Events and Event Delegation Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Register a listener | button.addEventListener('click', handleClick) | View examples |
| Listen once | button.addEventListener('click', initialize, { once: true }) | View examples |
| Group listener cleanup | panel.addEventListener('input', update, { signal: controller.signal }) | View examples |
| Remove a listener | button.removeEventListener('click', handleClick) | View examples |
| Observe the capture phase | document.addEventListener('click', inspect, { capture: true }) | View examples |
| Read the listener target | const container = event.currentTarget | View examples |
| Stop further propagation | event.stopPropagation() | View examples |
| Resolve a delegated action | const action = event.target instanceof Element ? event.target.closest('[data-action]') : null | View examples |
| Verify delegation ownership | if (!menu.contains(action)) return | View examples |
| Cancel a default action | if (event.cancelable) event.preventDefault() | View examples |
| Declare a passive listener | window.addEventListener('touchmove', observe, { passive: true }) | View examples |
| Inspect cancellation | if (event.defaultPrevented) return | View examples |
| Create an application event | const event = new CustomEvent('cart:add', { detail: { sku: 'A42' } }) | View examples |
| Dispatch synchronously | const accepted = cart.dispatchEvent(event) | View examples |
| Inspect the event path | const path = event.composedPath() | View examples |
| Cross a shadow boundary | new CustomEvent('widget:change', { bubbles: true, composed: true }) | View examples |
| Prefer activation events | button.addEventListener('click', activate) | View examples |
| Read a logical key | if (event.key === 'Escape') closeDialog() | View examples |
DOM and Lifecycle · 13 commands
Document Lifecycle and Page Visibility Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Inspect readiness | document.readyState | View examples |
| Wait for parsed DOM | document.addEventListener('DOMContentLoaded', init, { once: true }) | View examples |
| Wait for page load | window.addEventListener('load', measureAssets, { once: true }) | View examples |
| Initialize late or early | document.readyState === 'loading' ? document.addEventListener('DOMContentLoaded', init) : init() | View examples |
| Read visibility | document.visibilityState === 'hidden' | View examples |
| Observe visibility | document.addEventListener('visibilitychange', syncWork) | View examples |
| Handle page activation | window.addEventListener('pageshow', restoreTransientState) | View examples |
| Handle page deactivation | window.addEventListener('pagehide', releaseTransientResources) | View examples |
| Detect cached restoration | if (event.persisted) refreshVolatileData() | View examples |
| Warn about unsaved work | window.addEventListener('beforeunload', event => event.preventDefault()) | View examples |
| Avoid unload handlers | window.addEventListener('pagehide', cleanup) | View examples |
| Queue a small beacon | navigator.sendBeacon('/session', payload) | View examples |
| Send with fetch options | fetch('/session', { method: 'POST', body: payload, keepalive: true }) | View examples |
DOM and Lifecycle · 15 commands
DOM Selection and Range API Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Create a collapsed range | const range = document.createRange() | View examples |
| Set text boundaries | range.setStart(textNode, 2); range.setEnd(textNode, 7) | View examples |
| Select a node | range.selectNode(element) | View examples |
| Select node contents | range.selectNodeContents(element) | View examples |
| Read document selection | const selection = document.getSelection() | View examples |
| Guard an empty selection | if (selection && selection.rangeCount > 0) selection.getRangeAt(0) | View examples |
| Display a range | selection.removeAllRanges(); selection.addRange(range) | View examples |
| Observe selection changes | document.addEventListener('selectionchange', updateToolbar) | View examples |
| Clone selected content | const fragment = range.cloneContents() | View examples |
| Move selected content out | const fragment = range.extractContents() | View examples |
| Insert at a boundary | range.insertNode(document.createTextNode('Note')) | View examples |
| Measure line fragments | const rects = range.getClientRects() | View examples |
| Compare two starts | a.compareBoundaryPoints(Range.START_TO_START, b) | View examples |
| Read textarea offsets | const selected = field.value.slice(field.selectionStart, field.selectionEnd) | View examples |
| Map across shadow roots | selection.getComposedRanges({ shadowRoots: [root] }) | View examples |
DOM and Lifecycle · 21 commands
DOM Traversal and Manipulation Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Select the first match | const submit = form.querySelector('button[type="submit"]') | View examples |
| Select a static snapshot | const rows = table.querySelectorAll('tbody > tr') | View examples |
| Escape a selector value | const item = document.querySelector(`#${CSS.escape(rawId)}`) | View examples |
| Test an element | if (element.matches('[aria-current]')) markActive(element) | View examples |
| Find the nearest match | const card = button.closest('[data-card]') | View examples |
| Skip non-element siblings | const nextItem = item.nextElementSibling | View examples |
| Read live element children | const liveItems = list.children | View examples |
| Create a filtered tree walk | const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT) | View examples |
| Create an element | const item = document.createElement('li') | View examples |
| Set literal text | item.textContent = userValue | View examples |
| Stage nodes in a fragment | const fragment = document.createDocumentFragment() | View examples |
| Append nodes and text | card.append(title, ' — ', summary) | View examples |
| Move a node to the start | list.prepend(list.lastElementChild) | View examples |
| Insert before a sibling | reference.before(newNode) | View examples |
| Replace all children | container.replaceChildren(emptyState) | View examples |
| Replace one node | placeholder.replaceWith(content) | View examples |
| Clone a subtree | const copy = template.content.cloneNode(true) | View examples |
| Import a cross-document copy | const copy = document.importNode(source, true) | View examples |
| Adopt a cross-document node | const moved = document.adoptNode(source) | View examples |
| Remove a node | notice.remove() | View examples |
| Observe child mutations | observer.observe(list, { childList: true, subtree: true }) | View examples |
DOM and Lifecycle · 11 commands
HTML Templates, Slots, and Custom Elements Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Declare a template | <template id="card-template">
<article>
<slot>
</slot>
</article>
</template> | View examples |
| Clone template content | const fragment = template.content.cloneNode(true) | View examples |
| Register an element | customElements.define('status-card', StatusCard) | View examples |
| Handle connection | connectedCallback() { this.render(); } | View examples |
| Observe attributes | static observedAttributes = ['status'] | View examples |
| React to an attribute | attributeChangedCallback(name, oldValue, newValue) { this.render(); } | View examples |
| Attach an open shadow root | const root = this.attachShadow({ mode: 'open' }) | View examples |
| Project default content | <slot>Fallback text</slot> | View examples |
| Project named content | <slot name="actions"></slot> | View examples |
| Expose a style part | <button part="button"><slot></slot></button> | View examples |
| Wait for registration | await customElements.whenDefined('status-card') | View examples |
DOM and Lifecycle · 18 commands
Mutation, Intersection, and Resize Observers Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Create a mutation observer | const observer = new MutationObserver(records => process(records)) | View examples |
| Observe selected mutations | observer.observe(root, { childList: true, subtree: true }) | View examples |
| Filter attributes | observer.observe(node, { attributes: true, attributeFilter: ['aria-expanded'] }) | View examples |
| Request old values | observer.observe(node, { attributes: true, attributeOldValue: true }) | View examples |
| Drain pending records | const pending = observer.takeRecords() | View examples |
| Create an intersection observer | const observer = new IntersectionObserver(onIntersect, { threshold: [0, 0.5, 1] }) | View examples |
| Expand the root boundary | new IntersectionObserver(callback, { rootMargin: '0px 0px 300px' }) | View examples |
| Observe an intersection target | observer.observe(document.querySelector('[data-lazy]')) | View examples |
| Check visible intersection | if (entry.isIntersecting) reveal(entry.target) | View examples |
| Stop tracking one target | observer.unobserve(entry.target) | View examples |
| Drain intersection entries | const pending = observer.takeRecords() | View examples |
| Create a resize observer | const observer = new ResizeObserver(entries => update(entries)) | View examples |
| Observe the border box | observer.observe(panel, { box: 'border-box' }) | View examples |
| Read logical box size | const { inlineSize, blockSize } = entry.contentBoxSize[0] | View examples |
| Read the legacy fallback | const width = entry.contentRect.width | View examples |
| Stop observing one element | observer.unobserve(panel) | View examples |
| Disconnect an observer | observer.disconnect() | View examples |
| Feature-detect support | if ('ResizeObserver' in globalThis) startResizeTracking() | View examples |
DOM and Lifecycle · 15 commands
Performance Timing and Observers Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Detect observable types | const types = PerformanceObserver.supportedEntryTypes | View examples |
| Observe buffered entries | observer.observe({ type: 'largest-contentful-paint', buffered: true }) | View examples |
| Drain queued records | const pending = observer.takeRecords() | View examples |
| Stop observation | observer.disconnect() | View examples |
| Read navigation timing | const [nav] = performance.getEntriesByType('navigation') | View examples |
| Compute response wait | const ttfb = nav.responseStart - nav.requestStart | View examples |
| Read resource timings | const resources = performance.getEntriesByType('resource') | View examples |
| Expose cross-origin detail | Timing-Allow-Origin: https://app.example | View examples |
| Clear the resource buffer | performance.clearResourceTimings() | View examples |
| Mark a workflow point | performance.mark('checkout:start') | View examples |
| Measure between marks | performance.measure('checkout', 'checkout:start', 'checkout:end') | View examples |
| Clear application marks | performance.clearMarks('checkout:start') | View examples |
| Read first contentful paint | performance.getEntriesByName('first-contentful-paint', 'paint')[0] | View examples |
| Observe long interactions | observer.observe({ type: 'event', buffered: true, durationThreshold: 40 }) | View examples |
| Bound telemetry payloads | navigator.sendBeacon('/rum', new Blob([payload], { type: 'application/json' })) | View examples |
DOM and Lifecycle · 14 commands
Web Animations API Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Create an animation | const animation = element.animate(keyframes, { duration: 300, easing: 'ease-out' }) | View examples |
| Use property-indexed keyframes | element.animate({ opacity: [0, 1], transform: ['scale(.95)', 'scale(1)'] }, 200) | View examples |
| Set keyframe offsets | [{ opacity: 0, offset: 0 }, { opacity: 1, offset: 0.4 }, { opacity: 1, offset: 1 }] | View examples |
| Pause playback | animation.pause() | View examples |
| Reverse safely | animation.reverse() | View examples |
| Change playback rate | animation.updatePlaybackRate(0.5) | View examples |
| Seek to a time | animation.currentTime = 150 | View examples |
| Await completion | await animation.finished | View examples |
| Await pending operations | await animation.ready | View examples |
| Commit computed values | animation.commitStyles(); animation.cancel() | View examples |
| Inspect element animations | const animations = element.getAnimations({ subtree: true }) | View examples |
| Read computed timing | const timing = animation.effect.getComputedTiming() | View examples |
| Change effect timing | animation.effect.updateTiming({ duration: 500, iterations: 2 }) | View examples |
| Detect reduced motion | const reduce = matchMedia('(prefers-reduced-motion: reduce)').matches | View examples |
Networking and Offline · 16 commands
Fetch API and Streaming Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Fetch JSON | const response = await fetch('/api/items', { headers: { Accept: 'application/json' } }) | View examples |
| Reject an HTTP error | if (!response.ok) throw new Error(`HTTP ${response.status}`) | View examples |
| Consume JSON once | const data = await response.json() | View examples |
| Construct a Request | const request = new Request('/api/items', { method: 'GET', cache: 'no-cache' }) | View examples |
| Require a CORS response | await fetch('https://api.example/data', { mode: 'cors' }) | View examples |
| Include cross-origin credentials | await fetch(url, { mode: 'cors', credentials: 'include' }) | View examples |
| Enforce same-origin access | await fetch(url, { mode: 'same-origin' }) | View examples |
| Cancel with a controller | const controller = new AbortController(); fetch(url, { signal: controller.signal }) | View examples |
| Apply a deadline | await fetch(url, { signal: AbortSignal.timeout(5000) }) | View examples |
| Combine cancellation sources | const signal = AbortSignal.any([controller.signal, AbortSignal.timeout(5000)]) | View examples |
| Acquire a byte reader | const reader = response.body.getReader() | View examples |
| Decode streamed text | const textStream = response.body.pipeThrough(new TextDecoderStream()) | View examples |
| Pipe with cancellation | await response.body.pipeTo(destination, { signal }) | View examples |
| Check body disturbance | if (response.bodyUsed) throw new Error('Body already consumed') | View examples |
| Clone before reading | const auditCopy = response.clone() | View examples |
| Upload a stream | await fetch('/upload', { method: 'POST', body: stream, duplex: 'half' }) | View examples |
Networking and Offline · 23 commands
HTML Script, Stylesheet, and Resource Loading Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Run a parser-blocking script | <script src="/js/config.js"></script> | View examples |
| Defer a classic script | <script src="/js/app.js" defer></script> | View examples |
| Load an independent script | <script src="/js/analytics.js" async></script> | View examples |
| Load a JavaScript module | <script type="module" src="/js/app.js"></script> | View examples |
| Embed an inline module | <script type="module">
import { start } from "/js/app.js"; start();
</script> | View examples |
| Import code on demand | const { openHelp } = await import("/js/help.js"); | View examples |
| Map a bare module name | <script type="importmap">
{"imports":{"app":"/js/app.js"}}
</script> | View examples |
| Prepare a module early | <link rel="modulepreload" href="/js/app.js"> | View examples |
| Provide a legacy fallback | <script nomodule src="/js/legacy.js"></script> | View examples |
| Load an external stylesheet | <link rel="stylesheet" href="/css/site.css"> | View examples |
| Apply styles to matching media | <link
rel="stylesheet"
href="/css/print.css"
media="print"> | View examples |
| Embed document styles | <style>.notice { color: #9a3412; }</style> | View examples |
| Import CSS from CSS | @import url("/css/theme.css"); | View examples |
| Preload a stylesheet | <link rel="preload" href="/css/critical.css" as="style"> | View examples |
| Preload a web font | <link
rel="preload"
href="/fonts/inter.woff2"
as="font"
type="font/woff2"
crossorigin> | View examples |
| Open a connection early | <link
rel="preconnect"
href="https://cdn.example.com"
crossorigin> | View examples |
| Resolve an origin early | <link
rel="dns-prefetch"
href="https://analytics.example.com"> | View examples |
| Fetch a likely future resource | <link rel="prefetch" href="/next-page.html"> | View examples |
| Prioritize an important image | <img
src="/images/hero.webp"
alt="Product dashboard overview"
width="1200"
height="630"
fetchpriority="high"> | View examples |
| Defer an off-screen embed | <iframe
src="/embed/report"
title="Quarterly report preview"
width="800"
height="450"
loading="lazy">
</iframe> | View examples |
| Verify a cross-origin script | <script
src="https://example.com/example-framework.js"
integrity="sha384-Li9vy3DqF8tnTXuiaAJuML3ky+er10rcgNR/VqsVpcw+ThHmYcwiB1pbOxEbzJr7"
crossorigin="anonymous">
</script> | View examples |
| Limit a resource referrer | <script
src="https://cdn.example.com/widget.js"
referrerpolicy="no-referrer">
</script> | View examples |
| Provide a no-script fallback | <noscript>
<p>
JavaScript is required to open the interactive chart.
</p>
</noscript> | View examples |
Networking and Offline · 14 commands
Push Notifications and App Badging Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Register a service worker | const registration = await navigator.serviceWorker.register('/sw.js', { scope: '/' }) | View examples |
| Wait for an active worker | const registration = await navigator.serviceWorker.ready | View examples |
| Request notification permission | const permission = await Notification.requestPermission() | View examples |
| Read current permission | if (Notification.permission === 'granted') enablePush() | View examples |
| Create a push subscription | await registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey }) | View examples |
| Reuse a subscription | const subscription = await registration.pushManager.getSubscription() | View examples |
| Unsubscribe locally | await subscription.unsubscribe() | View examples |
| Extend a push event | event.waitUntil(handlePush(event)) | View examples |
| Show a notification | await self.registration.showNotification(title, options) | View examples |
| Replace related notifications | { tag: 'inbox', renotify: false } | View examples |
| Handle a notification click | self.addEventListener('notificationclick', event => event.waitUntil(openApp(event))) | View examples |
| Find application windows | const windows = await clients.matchAll({ type: 'window', includeUncontrolled: true }) | View examples |
| Set an application badge | await navigator.setAppBadge(unreadCount) | View examples |
| Clear the application badge | await navigator.clearAppBadge() | View examples |



