Skip to content

nicholaswmin/dom

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

12 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

test-workflow

dom

concise DOM api in ~ 400 bytes

code snippet showing a usage example
  • concise selectors: $('.foobar')
  • concise event methods: .on('event', fn) / .off('event', fn)
  • an additional css(..) method.
  • method-chaining

todo

  • fix CI tests
  • fix event tests
  • add a carbon snippet here
  • snippetify that code thing

rationale

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.

usage

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.

api

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'

tests

node --import ./test/setup.js --test

Note

requires: node v22+

misc

serve demo

npx serve

license

ISC License

@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.