concise DOM api in
~ 400 bytes
- concise selectors:
$('.foobar')
- concise event methods:
.on('event', fn)
/.off('event', fn)
- an additional
css(..)
method. - method-chaining
- fix CI tests
- fix event tests
- add a carbon snippet here
- snippetify that code thing
I often hack up short HTML sandboxes for testing a component I'm working on.
These boilerplate files are best kept stupidly-simple
so as not to distract from the actual component itself. In other words:
dont use a framework.
However, the native DOM API is annoyingly verbose even for the simplest of tasks, which ends up cluttering the file in and by itself.
Ergo, this.
The 3 methods covered here replace common but unbearably verbose DOM API methods with consice, chainable equivalents.
It doesn't cover everything but that's by design:
It's small API surface means there's nothing to memorise,
it's impossible to break & straightforward to understand,
even if you've never read a single word of this document.
Yes, it's like jQuery.
drop this:
<script type="module" src="https://cdn.jsdelivr.net/gh/nicholaswmin/dom@main/dom.js"></script>
or just copy/paste the source in your own project.
I use it as an editor code-snippet.
selecting elements:
$.$$('div') // select all divs
$.$('div') // select first matching
style props:
$.$$('div').css({ background: 'red' })
// all divs are now red
event listeners:
c.on('click', function(e) {
this.css({ color: 'red', cursor: 'pointer' })
// set styles
})
.on('mouseover', function(e) {
// is chainable
})
.css({ color: 'black' })
remove listeners:
// remove all click listeners
$.$$('div').off('click')
// remove all listeners, for all divs
$.$$('div').off()
actual DOM elements:
// actual DOM element
$.$('div').$
// actual DOM elements
$.$$('div').$$
// example
$.$('div').$.textContent = 'hello world'
node --import ./test/setup.js --test
Note
requires: node v22+
serve demo
npx serve
@nicholaswmin, 2024
Permission to use, copy, modify, and/or distribute or resell this software for any purpose is hereby granted without fee, provided that the above copyright notice and this permission notice appear in all copies.