| Signature | Brief description | Example |
|---|---|---|
| Selection & traversal | ||
document.querySelector(sel) | First match | const el = document.querySelector('#app') |
document.querySelectorAll(sel) | NodeList of matches | [...document.querySelectorAll('.item')] |
document.getElementById(id) | By id | document.getElementById('nav') |
element.closest(sel) | Nearest ancestor match | btn.closest('form') |
element.matches(sel) | Element matches selector? | if (el.matches('.active')) { … } |
element.parentElement | Parent element | el.parentElement.remove() |
element.children | HTMLCollection of children | [...el.children].length |
| Events | ||
element.addEventListener(type, fn, opts) | Listen for events | el.addEventListener('click', onClick, { once:true }) |
element.removeEventListener(type, fn) | Stop listening | el.removeEventListener('click', onClick) |
element.dispatchEvent(evt) | Fire custom event | el.dispatchEvent(new Event('refresh')) |
| Classes & attributes | ||
element.classList.add(...tokens) | Add class(es) | el.classList.add('active') |
element.classList.remove(...tokens) | Remove class(es) | el.classList.remove('hidden') |
element.classList.toggle(token[, force]) | Toggle class | el.classList.toggle('open', isOpen) |
element.className | Class string | el.className = 'card raised' |
element.setAttribute(name, value) | Set attribute | el.setAttribute('aria-live', 'polite') |
element.getAttribute(name) | Read attribute | el.getAttribute('role') |
element.removeAttribute(name) | Remove attribute | el.removeAttribute('disabled') |
element.hasAttribute(name) | Has attribute? | el.hasAttribute('hidden') |
| Content & DOM mutation | ||
element.textContent | Set / read text | el.textContent = 'Hello' |
element.innerHTML | Set / read HTML | el.innerHTML = '<b>Hi</b>' |
element.insertAdjacentHTML(pos, html) | Insert HTML | el.insertAdjacentHTML('beforeend', '<li>…</li>') |
element.append(...nodes) | Append nodes/text | el.append(child) |
element.prepend(...nodes) | Prepend nodes | el.prepend(title) |
element.replaceWith(node) | Replace self | el.replaceWith(newEl) |
element.remove() | Detach from DOM | el.remove() |
document.createElement(tag) | New element | const div = document.createElement('div') |
| Styles | ||
element.style.prop | Inline style property | el.style.backgroundColor = '#222' |
style.setProperty(name, value[, priority]) | Set (incl. !important) | el.style.setProperty('margin', '0', 'important') |
style.getPropertyValue(name) | Read inline value | el.style.getPropertyValue('--gap') |
getComputedStyle(el[, pseudo]) | Resolved styles | getComputedStyle(el).color |
| Geometry & scrolling | ||
element.getBoundingClientRect() | Box metrics | const { top } = el.getBoundingClientRect() |
element.scrollIntoView(opts) | Scroll to element | el.scrollIntoView({ behavior: 'smooth' }) |
window.scrollX / scrollY | Page scroll offsets | if (scrollY > 100) { … } |
| Storage & network | ||
localStorage.setItem/getItem/removeItem | Persistent key-value | localStorage.setItem('theme', 'dark') |
sessionStorage.setItem/… | Per-tab storage | sessionStorage.getItem('token') |
fetch(url, options) | HTTP requests | await fetch('/api/data') |
| Timing & animation | ||
setTimeout(fn, ms) / clearTimeout(id) | Delay a task | const id = setTimeout(run, 200) |
setInterval(fn, ms) / clearInterval(id) | Repeat task | setInterval(tick, 1000) |
requestAnimationFrame(fn) | Frame-synced callback | raf = requestAnimationFrame(step) |
element.animate(keyframes, options) | Web Animations API | el.animate({ opacity:[0,1] }, 300) |
matchMedia(query) | Watch media state | matchMedia('(prefers-color-scheme:dark)').matches |
| CSS property | JS (element.style.*) |
Example (JS) |
|---|---|---|
| Custom properties | ||
| --custom-prop | setProperty / getPropertyValue | el.style.setProperty('--brand', '#0af') |
| Color & background | ||
| color | color | el.style.color = 'rebeccapurple' |
| background | background | el.style.background = 'linear-gradient(#000,#333)' |
| background-color | backgroundColor | el.style.backgroundColor = 'tomato' |
| background-image | backgroundImage | el.style.backgroundImage = "url('bg.png')" |
| background-size / position | backgroundSize / backgroundPosition | el.style.backgroundSize = 'cover' |
| opacity | opacity | el.style.opacity = '0.7' |
| Typography | ||
| font | font | el.style.font = "italic 600 1rem/1.4 Inter" |
| font-family / font-size / font-weight | fontFamily / fontSize / fontWeight | el.style.fontSize = '18px' |
| line-height / letter-spacing | lineHeight / letterSpacing | el.style.lineHeight = '1.6' |
| text-align / text-decoration | textAlign / textDecoration | el.style.textAlign = 'center' |
| text-overflow / white-space | textOverflow / whiteSpace | el.style.textOverflow = 'ellipsis' |
| text-shadow | textShadow | el.style.textShadow = '0 1px 2px rgba(0,0,0,.3)' |
| user-select | userSelect | el.style.userSelect = 'none' |
| Box model | ||
| width / height / min- / max- | width / height / minWidth / maxWidth … | el.style.width = '320px' |
| margin / padding | margin / padding | el.style.margin = '1rem auto' |
| border / border-radius | border / borderRadius | el.style.border = '1px solid #ddd' |
| outline / outline-offset | outline / outlineOffset | el.style.outline = '2px solid #09f' |
| box-sizing / box-shadow | boxSizing / boxShadow | el.style.boxSizing = 'border-box' |
| aspect-ratio | aspectRatio | el.style.aspectRatio = '16 / 9' |
| Display & position | ||
| display / visibility | display / visibility | el.style.display = 'grid' |
| position / inset / top / right / bottom / left | position / inset / top … | el.style.position = 'absolute' |
| z-index / float / clear | zIndex / cssFloat / clear | el.style.zIndex = '10' |
| overflow / overflow-x / overflow-y | overflow / overflowX / overflowY | el.style.overflow = 'auto' |
| cursor / pointer-events | cursor / pointerEvents | el.style.cursor = 'pointer' |
| filter / backdrop-filter | filter / backdropFilter | el.style.filter = 'grayscale(1)' |
| will-change | willChange | el.style.willChange = 'transform' |
| Flexbox | ||
| flex-direction / flex-wrap / flex-flow | flexDirection / flexWrap / flexFlow | el.style.flexDirection = 'row-reverse' |
| justify-content / align-items / align-content | justifyContent / alignItems / alignContent | el.style.justifyContent = 'space-between' |
| gap / row-gap / column-gap | gap / rowGap / columnGap | el.style.gap = '1rem' |
| order / flex-grow / flex-shrink / flex-basis | order / flexGrow / flexShrink / flexBasis | child.style.flexGrow = '1' |
| align-self / place-content / place-items | alignSelf / placeContent / placeItems | child.style.alignSelf = 'flex-end' |
| Grid | ||
| grid-template-columns / rows / areas | gridTemplateColumns / Rows / Areas | el.style.gridTemplateColumns = 'repeat(3, 1fr)' |
| grid-auto-columns / rows / flow | gridAutoColumns / Rows / Flow | el.style.gridAutoRows = 'minmax(2rem, auto)' |
| grid-column / row / area | gridColumn / gridRow / gridArea | item.style.gridColumn = '1 / 3' |
| Transforms, transitions, animations | ||
| transform / transform-origin / perspective | transform / transformOrigin / perspective | el.style.transform = 'translateY(10px) scale(.9)' |
| transition | transition | el.style.transition = 'opacity .3s ease' |
| transition-property / -duration / -timing-function / -delay | transitionProperty / Duration / TimingFunction / Delay | el.style.transitionDuration = '200ms' |
| animation-name / -duration / -iteration-count / -direction | animationName / Duration / IterationCount / Direction | el.style.animationName = 'pulse' |
| Misc | ||
| scroll-behavior / scroll-snap-type / scroll-snap-align | scrollBehavior / scrollSnapType / scrollSnapAlign | el.style.scrollBehavior = 'smooth' |
| object-fit / object-position | objectFit / objectPosition | img.style.objectFit = 'cover' |
| list-style-type / list-style-position | listStyleType / listStylePosition | el.style.listStyleType = 'decimal' |
| border-collapse / table-layout | borderCollapse / tableLayout | el.style.tableLayout = 'fixed' |
| (any) + !important | setProperty(name, value, 'important') | el.style.setProperty('margin', '0', 'important') |
| Context / API | Method / Property | Purpose / Example |
|---|---|---|
Inline styles — CSSStyleDeclaration | ||
| Inline style object | element.style | Access / write the element's inline styles. |
| Set property | style.setProperty(name, value[, priority]) | el.style.setProperty('--brand', '#0af', 'important') |
| Get property | style.getPropertyValue(name) | style.getPropertyValue('--brand') → #0af |
| Remove property | style.removeProperty(name) | style.removeProperty('--brand') |
| Inline CSS text | style.cssText | style.cssText = 'color:red;' |
Class-based styling — classList | ||
| Add / remove | add(...tokens), remove(...tokens) | el.classList.add('active', 'wide') |
| Toggle | toggle(token[, force]) | el.classList.toggle('hidden', false) |
| Replace | replace(old, next) | el.classList.replace('old', 'new') |
| Query | contains(token), length | el.classList.contains('active') |
| Computed styles — resolved values | ||
| Get computed | getComputedStyle(element[, pseudo]) | getComputedStyle(el).getPropertyValue('color') |
| Stylesheets & rules (CSSOM) | ||
| All sheets | document.styleSheets | Enumerate attached stylesheets. |
| Insert / delete rule | sheet.insertRule(rule, i), deleteRule(i) | sheet.insertRule('.box{gap:1rem}', sheet.cssRules.length) |
| Constructable sheet | new CSSStyleSheet(), sheet.replaceSync(text) | const s = new CSSStyleSheet(); s.replaceSync(':root{--c:#09f}') |
| Adopt sheet | document.adoptedStyleSheets | document.adoptedStyleSheets = [...document.adoptedStyleSheets, s] |
| CSS Custom Properties | ||
| Set / get / remove | style.setProperty('--x','10px'), getPropertyValue('--x'), removeProperty('--x') | Scope to element or document.documentElement for global. |
| Media queries in JS | ||
| Query | matchMedia(query) | const m = matchMedia('(prefers-color-scheme:dark)') |
| Listen | m.addEventListener('change', fn) | Respond to media-condition changes. |
| Web Animations API | ||
| Animate | element.animate(keyframes, options) | el.animate([{opacity:0},{opacity:1}], {duration:300}) |
| Control | animation.play(), .pause(), .reverse(), .cancel() | Imperatively control animated state. |
| Window API (signature) | Brief description | Example |
|---|---|---|
| Identity & frame tree | ||
window / self | Global object | self === window |
top, parent, opener | Frame tree refs | if (window !== top) { /* in iframe */ } |
frames[i] / frames['name'] | Child frame windows | frames[0].postMessage('ping', '*') |
| Document & DOM | ||
document | Active document | document.title = 'Hello' |
getComputedStyle(el[, pseudo]) | Resolved styles | getComputedStyle(el).color |
customElements | Custom elements registry | customElements.define('x-box', Box) |
| Navigation | ||
location | URL / navigation | location.href = '/login' |
history.back() / .go(n) / .pushState() | Session history | history.back() |
open(url, target, features) | Open new window/tab | open('/help', '_blank') |
| Focus, dialogs, print | ||
focus() / blur() | Focus/defocus window | window.focus() |
alert(msg) / confirm(msg) / prompt(msg) | Modal dialogs | if (confirm('Delete?')) { … } |
print() | Open print dialog | print() |
| Timers & scheduling | ||
setTimeout(fn, ms) / clearTimeout(id) | Run once after delay | const t = setTimeout(run, 200) |
setInterval(fn, ms) / clearInterval(id) | Run repeatedly | setInterval(tick, 1000) |
requestAnimationFrame(fn) | Frame-synced callback | raf = requestAnimationFrame(step) |
queueMicrotask(fn) | Microtask queue | queueMicrotask(flush) |
| Size, screen & viewport | ||
innerWidth / innerHeight | Viewport size | if (innerWidth < 768) { … } |
devicePixelRatio | CSS px → device px | if (devicePixelRatio > 1) { … } |
screen | Screen info | screen.availWidth |
| Scrolling | ||
scrollX / scrollY | Scroll offsets | if (scrollY > 100) { … } |
scrollTo(x,y|opts) / scrollBy(dx,dy|opts) | Programmatic scroll | scrollTo({ top:0, behavior:'smooth' }) |
| Events & messaging | ||
addEventListener(type, fn[, opts]) | Listen for events | addEventListener('resize', onResize) |
postMessage(msg, targetOrigin) | Cross-doc messaging | other.postMessage({ ok:true }, '*') |
matchMedia(query) | Media query state | matchMedia('(prefers-color-scheme:dark)').matches |
| Networking & storage | ||
fetch(input, init) | HTTP requests | await fetch('/api') |
localStorage / sessionStorage | Key/value storage | localStorage.setItem('theme', 'dark') |
indexedDB | Client DB (async) | indexedDB.open('db', 1) |
structuredClone(value) | Deep structured clone | const copy = structuredClone(obj) |
| Workers & channels | ||
new Worker(url) | Background thread | new Worker('/w.js') |
new BroadcastChannel(name) | Tab-to-tab messaging | new BroadcastChannel('sync') |
| Crypto & performance | ||
crypto.getRandomValues(typedArray) | Secure random | crypto.getRandomValues(new Uint8Array(16)) |
performance.now() | High-res timestamp | const t0 = performance.now() |
| URLs & encoding | ||
new URL(href[, base]) / URLSearchParams | URL parsing / build | new URL('/p', location.origin) |
atob(str) / btoa(str) | Base64 decode / encode | atob('SGk=') |
window.open(...)| Feature | Example | Description | Default | Modern Support |
|---|---|---|---|---|
| width | width=600 | Sets content area width in pixels. | Browser default | Yes |
| height | height=400 | Sets content area height in pixels. | Browser default | Yes |
| left | left=100 | Distance from left edge of screen. | Centered | Yes |
| top | top=50 | Distance from top edge of screen. | Centered | Yes |
| menubar | menubar=no | Show or hide browser menu bar. | yes | Partial |
| toolbar | toolbar=no | Show or hide navigation toolbar. | yes | Partial |
| scrollbars | scrollbars=yes | Allow scrollbars if needed. | yes | Yes |
| resizable | resizable=yes | Allow window resizing. | yes | Yes |
| noopener | noopener | Block access to window.opener. | no | Yes |
| noreferrer | noreferrer | No Referer header; also blocks opener. | no | Yes |
| fullscreen | fullscreen=yes | Open in fullscreen mode. | no | Limited |