JS Story

JS Story: DOM and Styles

DOM manipulation, CSS properties, window API

4.0 DOM Manipulation

JavaScript is primarily used to observe and mutate elements in the document. The table below lists the most-used methods grouped by purpose: selection, events, class/attribute manipulation, content mutation, styles, geometry, and timing. Common patterns before the table:
// 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();
});
Table 1. - JavaScript Element Methods and Properties
Signature Brief description Example
Selection & traversal
document.querySelector(sel)First matchdocument.querySelector('#app')
document.querySelectorAll(sel)NodeList of matches[...document.querySelectorAll('.item')]
document.getElementById(id)By iddocument.getElementById('nav')
element.closest(sel)Nearest ancestor matchbtn.closest('form')
element.matches(sel)Element matches selector?if (el.matches('.active')) { ... }
element.parentElementParent elementel.parentElement.remove()
element.childrenHTMLCollection of children[...el.children].length
Events
element.addEventListener(type, fn, opts)Listen for eventsel.addEventListener('click', onClick, { once:true })
element.removeEventListener(type, fn)Stop listeningel.removeEventListener('click', onClick)
element.dispatchEvent(evt)Fire custom eventel.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 classel.classList.toggle('open', isOpen)
element.setAttribute(name, value)Set attributeel.setAttribute('aria-live', 'polite')
element.getAttribute(name)Read attributeel.getAttribute('role')
element.removeAttribute(name)Remove attributeel.removeAttribute('disabled')
Content & DOM mutation
element.textContentSet / read textel.textContent = 'Hello'
element.innerHTMLSet / read HTMLel.innerHTML = '<b>Hi</b>'
element.insertAdjacentHTML(pos, html)Insert HTMLel.insertAdjacentHTML('beforeend', '<li>...</li>')
element.append(...nodes)Append nodes/textel.append(child)
element.prepend(...nodes)Prepend nodesel.prepend(title)
element.replaceWith(node)Replace selfel.replaceWith(newEl)
element.remove()Detach from DOMel.remove()
document.createElement(tag)New elementdocument.createElement('div')
Styles
element.style.propInline style propertyel.style.backgroundColor = '#222'
style.setProperty(name, val[, priority])Set (incl. !important)el.style.setProperty('margin', '0', 'important')
getComputedStyle(el[, pseudo])Resolved stylesgetComputedStyle(el).color
Geometry & scrolling
element.getBoundingClientRect()Box metricsconst { top } = el.getBoundingClientRect()
element.scrollIntoView(opts)Scroll to elementel.scrollIntoView({ behavior: 'smooth' })
Timing & animation
setTimeout(fn, ms) / clearTimeout(id)Delay a taskconst id = setTimeout(run, 200)
setInterval(fn, ms) / clearInterval(id)Repeat tasksetInterval(tick, 1000)
requestAnimationFrame(fn)Frame-synced callbackraf = requestAnimationFrame(step)
element.animate(keyframes, opts)Web Animations APIel.animate([{opacity:0},{opacity:1}], 300)

4.1 CSS Properties via JavaScript

Every CSS property has a camelCase equivalent accessible through element.style. The table covers common CSS properties grouped by category with their JavaScript names.
Table 2. - CSS Properties and JavaScript Equivalents
CSS property JS (element.style.*) Example (JS)
Custom properties
--custom-propsetProperty / getPropertyValueel.style.setProperty('--brand', '#0af')
Color & background
colorcolorel.style.color = 'rebeccapurple'
background-colorbackgroundColorel.style.backgroundColor = 'tomato'
background-imagebackgroundImageel.style.backgroundImage = "url('bg.png')"
opacityopacityel.style.opacity = '0.7'
Typography
font-family / font-size / font-weightfontFamily / fontSize / fontWeightel.style.fontSize = '18px'
line-height / letter-spacinglineHeight / letterSpacingel.style.lineHeight = '1.6'
text-align / text-overflowtextAlign / textOverflowel.style.textAlign = 'center'
Box model
width / height / min- / max-width / height / minWidth / maxWidthel.style.width = '320px'
margin / paddingmargin / paddingel.style.margin = '1rem auto'
border / border-radiusborder / borderRadiusel.style.border = '1px solid #ddd'
box-sizing / box-shadowboxSizing / boxShadowel.style.boxSizing = 'border-box'
Display & position
display / visibilitydisplay / visibilityel.style.display = 'grid'
position / inset / top / right / bottom / leftposition / inset / top / ...el.style.position = 'absolute'
z-index / overflowzIndex / overflowel.style.zIndex = '10'
Flexbox
flex-direction / flex-wrapflexDirection / flexWrapel.style.flexDirection = 'row-reverse'
justify-content / align-itemsjustifyContent / alignItemsel.style.justifyContent = 'space-between'
gap / flex-grow / flex-shrinkgap / flexGrow / flexShrinkchild.style.flexGrow = '1'
Grid
grid-template-columns / rows / areasgridTemplateColumns / Rows / Areasel.style.gridTemplateColumns = 'repeat(3, 1fr)'
grid-column / row / areagridColumn / gridRow / gridAreaitem.style.gridColumn = '1 / 3'
Transforms & transitions
transformtransformel.style.transform = 'translateY(10px) scale(.9)'
transitiontransitionel.style.transition = 'opacity .3s ease'

4.2 Computed and Dynamic Styles

The dynamic style API covers reading resolved (computed) styles, manipulating class lists, working with CSSOM stylesheet rules, and using CSS custom properties at runtime.
// 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');
Table 3. - Computed and Dynamic Style Methods
Context / API Method / Property Purpose / Example
Inline styles - CSSStyleDeclaration
Inline style objectelement.styleAccess / write inline styles directly.
Set propertystyle.setProperty(name, value[, priority])el.style.setProperty('--brand', '#0af')
Get propertystyle.getPropertyValue(name)style.getPropertyValue('--brand')#0af
Remove propertystyle.removeProperty(name)style.removeProperty('--brand')
Class-based styling - classList
Add / removeadd(...tokens), remove(...tokens)el.classList.add('active', 'wide')
Toggletoggle(token[, force])el.classList.toggle('hidden', false)
Replacereplace(old, next)el.classList.replace('old', 'new')
Querycontains(token), lengthel.classList.contains('active')
Computed styles - resolved values
Get computedgetComputedStyle(element[, pseudo])getComputedStyle(el).getPropertyValue('color')
Stylesheets & rules (CSSOM)
All sheetsdocument.styleSheetsEnumerate attached stylesheets.
Insert / delete rulesheet.insertRule(rule, i), deleteRule(i)sheet.insertRule('.box{gap:1rem}', sheet.cssRules.length)
Media queries in JS
QuerymatchMedia(query)matchMedia('(prefers-color-scheme:dark)').matches
Listenm.addEventListener('change', fn)Respond to media-condition changes at runtime.

4.3 Window Object API

The window object is the global object in a browser context. It provides access to the document, navigation, history, storage, timers, messaging, and device APIs. Frame-tree references (window.top, window.parent) are how multi-frame sites communicate.
Table 4. - Window Object API
Window API (signature) Brief description Example
Identity & frame tree
window / selfGlobal objectself === window
top, parent, openerFrame tree refsif (window !== top) { /* in iframe */ }
frames[i] / frames['name']Child frame windowsframes[0].postMessage('ping', '*')
Document & DOM
documentActive documentdocument.title = 'Hello'
getComputedStyle(el[, pseudo])Resolved stylesgetComputedStyle(el).color
customElementsCustom elements registrycustomElements.define('x-box', Box)
Navigation
locationURL / navigationlocation.href = '/login'
history.back() / .go(n) / .pushState()Session historyhistory.pushState({}, '', '/page2')
open(url, target, features)Open new window/tabopen('/help', '_blank', 'noopener')
Timers & scheduling
setTimeout(fn, ms) / clearTimeout(id)Run once after delayconst t = setTimeout(run, 200)
setInterval(fn, ms) / clearInterval(id)Run repeatedlysetInterval(tick, 1000)
requestAnimationFrame(fn)Frame-synced callbackraf = requestAnimationFrame(step)
queueMicrotask(fn)Microtask queuequeueMicrotask(flush)
Size & scrolling
innerWidth / innerHeightViewport sizeif (innerWidth < 768) { ... }
scrollX / scrollYScroll offsetsif (scrollY > 100) { ... }
scrollTo(x,y|opts) / scrollBy(dx,dy|opts)Programmatic scrollscrollTo({ top:0, behavior:'smooth' })
Events & messaging
addEventListener(type, fn[, opts])Listen for eventsaddEventListener('resize', onResize)
postMessage(msg, targetOrigin)Cross-doc messagingother.postMessage({ ok:true }, '*')
matchMedia(query)Media query statematchMedia('(prefers-color-scheme:dark)').matches
Networking & storage
fetch(input, init)HTTP requestsawait fetch('/api')
localStorage / sessionStorageKey/value storagelocalStorage.setItem('theme', 'dark')
structuredClone(value)Deep cloneconst copy = structuredClone(obj)
Workers & channels
new Worker(url)Background threadnew Worker('/worker.js')
new BroadcastChannel(name)Tab-to-tab messagingnew BroadcastChannel('sync')
Crypto & performance
crypto.randomUUID() / getRandomValues(arr)Secure randomcrypto.randomUUID()
performance.now()High-res timestampconst t0 = performance.now()
URLs & encoding
new URL(href[, base]) / URLSearchParamsURL parsing / buildnew URL('/p', location.origin)
atob(str) / btoa(str)Base64 decode / encodeatob('SGk=')