Skip to main content

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โ€‹

APIChromeEdgeFirefoxSafariiOS SafariBaseline
Document.querySelectorโœ… 1+โœ… 12+โœ… 3.5+โœ… 3.1+โœ… 2+Widely available
Document.createElementโœ… 1+โœ… 12+โœ… 1+ [1]โœ… 1+โœ… 1+Widely available
  1. 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, or null
  • $$(selector, parent?) โ€” selects all matching elements as an array
  • createElement(tag, props?, ...children) โ€” creates an element with props and children
  • removeElement(el) โ€” removes an element from the DOM
  • setAttributes(el, attrs) โ€” sets multiple attributes at once
  • addClass(el, ...classes) โ€” adds one or more classes
  • removeClass(el, ...classes) โ€” removes one or more classes
  • toggleClass(el, className, force?) โ€” toggles a class, returns whether it's now present
  • hasClass(el, className) โ€” true if the element has the class
  • getData(el, key) โ€” reads a data-* attribute
  • setData(el, key, value) โ€” sets a data-* attribute

See the API reference for full signatures.