WebDev Story

WebDev Story: JavaScript DOM & Styles

DOM manipulation, CSS styles, window API

6.0 JavaScript DOM Manipulation Methods

JavaScript is primarily used to observe and mutate elements in a web page document. The table below lists the most-used methods grouped by purpose: selection, events, class/attribute manipulation, content mutation, styles, geometry, storage, and timing.
Table 1. — JavaScript Element Methods and Properties
Signature Brief description Example
Selection & traversal
document.querySelector(sel)First matchconst el = document.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.classNameClass stringel.className = 'card raised'
element.setAttribute(name, value)Set attributeel.setAttribute('aria-live', 'polite')
element.getAttribute(name)Read attributeel.getAttribute('role')
element.removeAttribute(name)Remove attributeel.removeAttribute('disabled')
element.hasAttribute(name)Has attribute?el.hasAttribute('hidden')
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 elementconst div = document.createElement('div')
Styles
element.style.propInline style propertyel.style.backgroundColor = '#222'
style.setProperty(name, value[, priority])Set (incl. !important)el.style.setProperty('margin', '0', 'important')
style.getPropertyValue(name)Read inline valueel.style.getPropertyValue('--gap')
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' })
window.scrollX / scrollYPage scroll offsetsif (scrollY > 100) { … }
Storage & network
localStorage.setItem/getItem/removeItemPersistent key-valuelocalStorage.setItem('theme', 'dark')
sessionStorage.setItem/…Per-tab storagesessionStorage.getItem('token')
fetch(url, options)HTTP requestsawait fetch('/api/data')
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, options)Web Animations APIel.animate({ opacity:[0,1] }, 300)
matchMedia(query)Watch media statematchMedia('(prefers-color-scheme:dark)').matches

6.1 Static CSS Styles via JavaScript

Every CSS property has a camelCase JavaScript equivalent accessible through element.style. The table covers all common CSS properties grouped by category, with their JavaScript names and examples.
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'
backgroundbackgroundel.style.background = 'linear-gradient(#000,#333)'
background-colorbackgroundColorel.style.backgroundColor = 'tomato'
background-imagebackgroundImageel.style.backgroundImage = "url('bg.png')"
background-size / positionbackgroundSize / backgroundPositionel.style.backgroundSize = 'cover'
opacityopacityel.style.opacity = '0.7'
Typography
fontfontel.style.font = "italic 600 1rem/1.4 Inter"
font-family / font-size / font-weightfontFamily / fontSize / fontWeightel.style.fontSize = '18px'
line-height / letter-spacinglineHeight / letterSpacingel.style.lineHeight = '1.6'
text-align / text-decorationtextAlign / textDecorationel.style.textAlign = 'center'
text-overflow / white-spacetextOverflow / whiteSpaceel.style.textOverflow = 'ellipsis'
text-shadowtextShadowel.style.textShadow = '0 1px 2px rgba(0,0,0,.3)'
user-selectuserSelectel.style.userSelect = 'none'
Box model
width / height / min- / max-width / height / minWidth / maxWidth …el.style.width = '320px'
margin / paddingmargin / paddingel.style.margin = '1rem auto'
border / border-radiusborder / borderRadiusel.style.border = '1px solid #ddd'
outline / outline-offsetoutline / outlineOffsetel.style.outline = '2px solid #09f'
box-sizing / box-shadowboxSizing / boxShadowel.style.boxSizing = 'border-box'
aspect-ratioaspectRatioel.style.aspectRatio = '16 / 9'
Display & position
display / visibilitydisplay / visibilityel.style.display = 'grid'
position / inset / top / right / bottom / leftposition / inset / top …el.style.position = 'absolute'
z-index / float / clearzIndex / cssFloat / clearel.style.zIndex = '10'
overflow / overflow-x / overflow-yoverflow / overflowX / overflowYel.style.overflow = 'auto'
cursor / pointer-eventscursor / pointerEventsel.style.cursor = 'pointer'
filter / backdrop-filterfilter / backdropFilterel.style.filter = 'grayscale(1)'
will-changewillChangeel.style.willChange = 'transform'
Flexbox
flex-direction / flex-wrap / flex-flowflexDirection / flexWrap / flexFlowel.style.flexDirection = 'row-reverse'
justify-content / align-items / align-contentjustifyContent / alignItems / alignContentel.style.justifyContent = 'space-between'
gap / row-gap / column-gapgap / rowGap / columnGapel.style.gap = '1rem'
order / flex-grow / flex-shrink / flex-basisorder / flexGrow / flexShrink / flexBasischild.style.flexGrow = '1'
align-self / place-content / place-itemsalignSelf / placeContent / placeItemschild.style.alignSelf = 'flex-end'
Grid
grid-template-columns / rows / areasgridTemplateColumns / Rows / Areasel.style.gridTemplateColumns = 'repeat(3, 1fr)'
grid-auto-columns / rows / flowgridAutoColumns / Rows / Flowel.style.gridAutoRows = 'minmax(2rem, auto)'
grid-column / row / areagridColumn / gridRow / gridAreaitem.style.gridColumn = '1 / 3'
Transforms, transitions, animations
transform / transform-origin / perspectivetransform / transformOrigin / perspectiveel.style.transform = 'translateY(10px) scale(.9)'
transitiontransitionel.style.transition = 'opacity .3s ease'
transition-property / -duration / -timing-function / -delaytransitionProperty / Duration / TimingFunction / Delayel.style.transitionDuration = '200ms'
animation-name / -duration / -iteration-count / -directionanimationName / Duration / IterationCount / Directionel.style.animationName = 'pulse'
Misc
scroll-behavior / scroll-snap-type / scroll-snap-alignscrollBehavior / scrollSnapType / scrollSnapAlignel.style.scrollBehavior = 'smooth'
object-fit / object-positionobjectFit / objectPositionimg.style.objectFit = 'cover'
list-style-type / list-style-positionlistStyleType / listStylePositionel.style.listStyleType = 'decimal'
border-collapse / table-layoutborderCollapse / tableLayoutel.style.tableLayout = 'fixed'
(any) + !importantsetProperty(name, value, 'important')el.style.setProperty('margin', '0', 'important')

6.2 Computed Styles — Dynamic Style API

The dynamic style API covers reading resolved (computed) styles, manipulating class lists, working with CSSOM stylesheet rules, and using CSS custom properties at runtime.
Table 3. — Computed and Dynamic Style Methods
Context / API Method / Property Purpose / Example
Inline styles — CSSStyleDeclaration
Inline style objectelement.styleAccess / write the element's inline styles.
Set propertystyle.setProperty(name, value[, priority])el.style.setProperty('--brand', '#0af', 'important')
Get propertystyle.getPropertyValue(name)style.getPropertyValue('--brand')#0af
Remove propertystyle.removeProperty(name)style.removeProperty('--brand')
Inline CSS textstyle.cssTextstyle.cssText = 'color:red;'
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)
Constructable sheetnew CSSStyleSheet(), sheet.replaceSync(text)const s = new CSSStyleSheet(); s.replaceSync(':root{--c:#09f}')
Adopt sheetdocument.adoptedStyleSheetsdocument.adoptedStyleSheets = [...document.adoptedStyleSheets, s]
CSS Custom Properties
Set / get / removestyle.setProperty('--x','10px'), getPropertyValue('--x'), removeProperty('--x')Scope to element or document.documentElement for global.
Media queries in JS
QuerymatchMedia(query)const m = matchMedia('(prefers-color-scheme:dark)')
Listenm.addEventListener('change', fn)Respond to media-condition changes.
Web Animations API
Animateelement.animate(keyframes, options)el.animate([{opacity:0},{opacity:1}], {duration:300})
Controlanimation.play(), .pause(), .reverse(), .cancel()Imperatively control animated state.

6.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.back()
open(url, target, features)Open new window/tabopen('/help', '_blank')
Focus, dialogs, print
focus() / blur()Focus/defocus windowwindow.focus()
alert(msg) / confirm(msg) / prompt(msg)Modal dialogsif (confirm('Delete?')) { … }
print()Open print dialogprint()
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, screen & viewport
innerWidth / innerHeightViewport sizeif (innerWidth < 768) { … }
devicePixelRatioCSS px → device pxif (devicePixelRatio > 1) { … }
screenScreen infoscreen.availWidth
Scrolling
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')
indexedDBClient DB (async)indexedDB.open('db', 1)
structuredClone(value)Deep structured cloneconst copy = structuredClone(obj)
Workers & channels
new Worker(url)Background threadnew Worker('/w.js')
new BroadcastChannel(name)Tab-to-tab messagingnew BroadcastChannel('sync')
Crypto & performance
crypto.getRandomValues(typedArray)Secure randomcrypto.getRandomValues(new Uint8Array(16))
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=')
Table 5. — Arguments for window.open(...)
Feature Example Description Default Modern Support
widthwidth=600Sets content area width in pixels.Browser defaultYes
heightheight=400Sets content area height in pixels.Browser defaultYes
leftleft=100Distance from left edge of screen.CenteredYes
toptop=50Distance from top edge of screen.CenteredYes
menubarmenubar=noShow or hide browser menu bar.yesPartial
toolbartoolbar=noShow or hide navigation toolbar.yesPartial
scrollbarsscrollbars=yesAllow scrollbars if needed.yesYes
resizableresizable=yesAllow window resizing.yesYes
noopenernoopenerBlock access to window.opener.noYes
noreferrernoreferrerNo Referer header; also blocks opener.noYes
fullscreenfullscreen=yesOpen in fullscreen mode.noLimited