// select, listen, mutate
const btn = document.querySelector('#go');
btn.addEventListener('click', () => {
const output = document.querySelector('#out');
output.textContent = 'Clicked!';
output.classList.toggle('highlight');
});
// create and append
const li = document.createElement('li');
li.textContent = 'New item';
document.querySelector('ul').append(li);
// remove on click (event delegation)
document.querySelector('ul').addEventListener('click', e => {
if (e.target.matches('li')) e.target.remove();
});
| Signature | Brief description | Example |
|---|---|---|
| Selection & traversal | ||
document.querySelector(sel) | First match | 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.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') |
| 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 | document.createElement('div') |
| Styles | ||
element.style.prop | Inline style property | el.style.backgroundColor = '#222' |
style.setProperty(name, val[, priority]) | Set (incl. !important) | el.style.setProperty('margin', '0', 'important') |
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' }) |
| 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, opts) | Web Animations API | el.animate([{opacity:0},{opacity:1}], 300) |
| 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-color | backgroundColor | el.style.backgroundColor = 'tomato' |
| background-image | backgroundImage | el.style.backgroundImage = "url('bg.png')" |
| opacity | opacity | el.style.opacity = '0.7' |
| Typography | ||
| 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-overflow | textAlign / textOverflow | el.style.textAlign = 'center' |
| 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' |
| box-sizing / box-shadow | boxSizing / boxShadow | el.style.boxSizing = 'border-box' |
| 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 / overflow | zIndex / overflow | el.style.zIndex = '10' |
| Flexbox | ||
| flex-direction / flex-wrap | flexDirection / flexWrap | el.style.flexDirection = 'row-reverse' |
| justify-content / align-items | justifyContent / alignItems | el.style.justifyContent = 'space-between' |
| gap / flex-grow / flex-shrink | gap / flexGrow / flexShrink | child.style.flexGrow = '1' |
| Grid | ||
| grid-template-columns / rows / areas | gridTemplateColumns / Rows / Areas | el.style.gridTemplateColumns = 'repeat(3, 1fr)' |
| grid-column / row / area | gridColumn / gridRow / gridArea | item.style.gridColumn = '1 / 3' |
| Transforms & transitions | ||
| transform | transform | el.style.transform = 'translateY(10px) scale(.9)' |
| transition | transition | el.style.transition = 'opacity .3s ease' |
// read computed (resolved) color - not the inline value
const color = getComputedStyle(el).color;
// set and read a CSS custom property on the root
document.documentElement.style.setProperty('--accent', '#0af');
const accent = getComputedStyle(document.documentElement)
.getPropertyValue('--accent').trim();
// toggle theme by swapping a class
document.body.classList.toggle('theme-dark');
| Context / API | Method / Property | Purpose / Example |
|---|---|---|
Inline styles - CSSStyleDeclaration | ||
| Inline style object | element.style | Access / write inline styles directly. |
| Set property | style.setProperty(name, value[, priority]) | el.style.setProperty('--brand', '#0af') |
| Get property | style.getPropertyValue(name) | style.getPropertyValue('--brand') → #0af |
| Remove property | style.removeProperty(name) | style.removeProperty('--brand') |
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) |
| Media queries in JS | ||
| Query | matchMedia(query) | matchMedia('(prefers-color-scheme:dark)').matches |
| Listen | m.addEventListener('change', fn) | Respond to media-condition changes at runtime. |
| 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.pushState({}, '', '/page2') |
open(url, target, features) | Open new window/tab | open('/help', '_blank', 'noopener') |
| 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 & scrolling | ||
innerWidth / innerHeight | Viewport size | if (innerWidth < 768) { ... } |
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') |
structuredClone(value) | Deep clone | const copy = structuredClone(obj) |
| Workers & channels | ||
new Worker(url) | Background thread | new Worker('/worker.js') |
new BroadcastChannel(name) | Tab-to-tab messaging | new BroadcastChannel('sync') |
| Crypto & performance | ||
crypto.randomUUID() / getRandomValues(arr) | Secure random | crypto.randomUUID() |
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=') |