Build a chainable css() helper with set, get, and unset
A small widget library wants a tiny helper for inline styles so components can write css('.toast').set({ opacity: 0, top: 12 }).set('zIndex', 50) instead of looping over elements and remembering when to add px.
Implement css(target). It returns a wrapper object with three methods:
const wrapper = css(target);
wrapper.set(name, value) // sets one inline style on every matched element; returns wrapper
wrapper.set(styles) // same, for each key/value of a plain object; returns wrapper
wrapper.get(name) // the inline value on the FIRST matched element
wrapper.unset(...names) // removes these inline styles from every matched element; returns wrapper
document (document.querySelectorAll).NodeList of elements.set and unset do nothing and still return the wrapper, and get returns undefined.backgroundColor) and kebab-case (background-color). Both refer to the same property.-- (for example --card-gap). Keep their name exactly as given.px appended (120 becomes '120px', 0 becomes '0px'), except for custom properties and these unitless properties, which use the plain number: opacity, z-index, font-weight, line-height, flex-grow, flex-shrink, order.null, undefined, or an empty string removes the property, like unset.get(name) returns the first matched element’s inline value as the browser reports it (element.style.getPropertyValue), or '' if that inline style is not set. Do not read computed styles.// <div class="toast">Saved</div> <div class="toast">Sent</div>
css('.toast')
.set({ opacity: 0.9, marginTop: 8, 'background-color': 'navy' })
.set('zIndex', 50);
// both toasts: opacity: 0.9; margin-top: 8px; background-color: navy; z-index: 50
css('.toast').get('margin-top'); // => '8px'
css('.toast').get('width'); // => ''
css('.missing').get('width'); // => undefined
css(document.querySelector('.toast')).set('--toast-gap', 4).get('--toast-gap'); // => '4'
css('.toast').set('opacity', null).unset('zIndex', 'margin-top');
// both toasts: background-color: navy