DOM Manipulation with Cash

17 Jul 2014 | By Alex Young | Tags libraries browser dom

Cash (GitHub: sudo-js / cash, License: MIT) by Rob Robbins at TaskRabbit, is a lightweight library for working with the DOM. It uses $ to provide access to an abstracted NodeList. It’s chainable, and supports events, CSS manipulation, and attributes.

For example, given var things = document.querySelectorAll('div'), you could change the class attributes like this:

$(things).q.forEach(function(el) { el.classList.remove('example'); });

Or add an event handler:

$(things).on('click', function() {
  // One of the things was clicked
});

The init method that runs whenever you call $() checks to see if the argument is an array, NodeList, or HTMLCollection. When it’s not an array, slice.call is used to map the elements to an array. The idea is to make this method as fast as possible so it’s safe to call it whenever you need access to a list of elements.

The new TaskRabbit site has been developed using micro libraries, and this is the library they used make working with the DOM more succinct. If you go to taskrabbit.com you should be able to run something like $(document.querySelectorAll('p')).q to see it in action.

If you’re avoiding larger frameworks and trying to find the perfect DOM querying and manipulation library, then take a look at the source – it’s fairly easy to see what’s going on. There’s annotated source, and the project itself is fairly easy to read because it uses a Node build script to generate the final framework from separate files. There are even detailed tests in the spec directory.


blog comments powered by Disqus