dom
Short-hand wrappers around common DOM operations โ querying, creating
elements, classes, attributes, and data-* attributes.
Import: @rtorcato/browser-common/dom
๐ MDN: Document Object Model
Browser supportโ
| API | Chrome | Edge | Firefox | Safari | iOS Safari | Baseline |
|---|---|---|---|---|---|---|
Document.querySelector | โ 1+ | โ 12+ | โ 3.5+ | โ 3.1+ | โ 2+ | Widely available |
Document.createElement | โ 1+ | โ 12+ | โ 1+ [1] | โ 1+ | โ 1+ | Widely available |
- Firefox: Doesn't conform to the DOM spec for XUL and XHTML documents: localName and namespaceURI are not set to null on the created element.
โ
supported ยท โ partial ยท โ not supported ยท [n] see note. Generated from MDN browser-compat-data and web-features. caniuse: Document.querySelector ยท Document.createElement
Exampleโ
import { $, $$, createElement, addClass, toggleClass, setData } from '@rtorcato/browser-common/dom'
const btn = $('button.primary')
const items = $$('.item')
const el = createElement('button', { className: 'primary' }, 'Save')
addClass(el, 'active')
toggleClass(el, 'open')
setData(el, 'userId', '42')
Exportsโ
$(selector, parent?)โ selects the first matching element, ornull$$(selector, parent?)โ selects all matching elements as an arraycreateElement(tag, props?, ...children)โ creates an element with props and childrenremoveElement(el)โ removes an element from the DOMsetAttributes(el, attrs)โ sets multiple attributes at onceaddClass(el, ...classes)โ adds one or more classesremoveClass(el, ...classes)โ removes one or more classestoggleClass(el, className, force?)โ toggles a class, returns whether it's now presenthasClass(el, className)โtrueif the element has the classgetData(el, key)โ reads adata-*attributesetData(el, key, value)โ sets adata-*attribute
See the API reference for full signatures.