DOM Element Class Tweaking (similar to classList native API)
A JS micro library for CSS class manipulation. classtweak works in conjuction with the new HTML5 Selectors API enabling you to tweak multiple elements and classes at once.
The classtweak library is designed to be simple to use and flexible.
The simplest case is calling
classtweak on a dom reference, with class modifiers:
var el = documentgetElementById'test';// add class 'bounce'classtweakel '+bounce';// remove class 'bounce'classtweakel '-bounce';// toggle class 'bounceclasstweakel '!bounce';// add class 'bounce' and toggle class 'slide'classtweakel '+bounce !slide';
NOTE: It is also possible to tweak multiple objects at once by passing an array of elements.
As an additional helper,
classtweak can return a function for tweaking the dom elements supplied in the original call:
var tweaker = classtweakdocumentgetElementById'test';// add class 'bounce'tweaker'+bounce';// remove class 'bounce'tweaker'-bounce';// toggle class 'bounce'tweaker'!bounce';// add class 'bounce' and toggle the class 'slide'tweaker'+bounce !slide';
You can also work with selectors as per the maturing Selectors API:
// add the class 'bounce' to all sections on the pageclasstweak'section' '+bounce';
By default, this is scoped at the
document level but can this can be overriden by supplying a third parameter for the HTML element that's subtree will be searched:
var testNode = documentgetElementById'test';// add the class 'bounce' to any sections that are children of the test nodeclasstweak'section' '+bounce' testNode;
As an option, I've also added an alternative modification syntax based on some feedback I received:
var el = documentgetElementById'test';// add class 'bounce'classtweakel '.bounce';// remove class 'bounce'classtweakel 'bounce.';// toggle class 'bounceclasstweakel '.bounce.';// add class 'bounce' and toggle class 'slide'classtweakel '.bounce .slide.';
I've also added chaining to classtweak so you can be really, really terse. The behaviour of chaining is sensitive to the context of the
classtweak call though so be aware of that.
If you want to tweak classes on a number of different elements with different class modifications you would call classtweak like:
classtweak'section' '-active''section[data-route="/"]' '+active';
Alternatively if you have created a tweaker on a set of target elements, you can chain those calls too:
In reality, though, this probably has limited value as you can achieve the same by simply passing through a space delimited string of all the class tweaks: