The two functions mentioned here, chainify (https://gist.github.com/gists/1466219) and propertize (https://gist.github.com/1466253) work fine on their own but best when used together.
When provided with a constructor such as Element
, Node
, CSSStyleDeclaration
, etc, the function will run through every property. If the property is a function, it will be wrapped in another function which will ensure that the return value is the original object.
This means that you can use the syntax
document.createElement('a')
.setAttribute('data-monkeys', '∞')
.addEventListener('click', function(){ alert('Urk! Alert!')}, false)
Similar to the chainify function, this takes a constructor as its argument. It adds the method .prop to everything which will set the properties provided either as an object or as a propertyName and propertyValue then return the original object to ensure the outcome is still chainable.
myElement
.prop({
'href': 'http://140byt.es/',
'title': 'tiny awsm'
})
.prop('innerHTML', '140byt.es');
When the two are combined, you have a completely chainable DOM manipulation tool.
The idea for the .prop function came from Lea Verou's Chainvas. This should be mostly compatible with the syntax (although possibly less robust). You can do the same chainify/propertize on any of the standard constructors - Element
, Node
, CSSStyleDeclaration
, DOMTokenList
, CanvasRenderingContext2D
to make any API chainable.
Note: These updates include calling the function on window.Element or window.Element.prototype
Seperate functions --------------------
Original prop - 174 bytes
var propertize=function(a,b,c){a.prototype.prop=function(){if(b=arguments,1 in b)this[b[0]]=b[1];else{b=b[0];for(c in b)this[c]=b[c]}return this}};propertize(window.Element);
Updated prop - 141 bytes
!function(a,b,c){a.prototype.prop=function(){b=arguments,1 in b?this[b[0]]=b[1]:b=b[0];for(c in b)this[c]=b[c];return this}}(window.Element);
Original chanify - 166 bytes
var chainify=function(a,b,c){for(a in b=a.prototype)with({d:b[a]})d.call?b[a]=function(){return(c=d.apply(this,arguments))===[]._?this:c}:0};chainify(window.Element);
Updated chanify - 129 bytes
!function(a,b){for(b in a=a.prototype)(function(c){a[b]=function(){return c.apply(this,arguments),this}})(a[b])}(window.Element);
Combined functions --------------------
Original prop and chanify - 336 bytes
var propertize=function(a,b,c){a.prototype.prop=function(){if(b=arguments,1 in b)this[b[0]]=b[1];else{b=b[0];for(c in b)this[c]=b[c]}return this}},chainify=function(a,b,c){for(a in b=a.prototype)with({d:b[a]})d.call?b[a]=function(){return(c=d.apply(this,arguments))===[]._?this:c}:0};propertize(window.Element),chainify(window.Element);
Updated prop and chanify - 228 bytes
!function(a,b,c){a.prop=function(){b=arguments,1 in b?this[b[0]]=b[1]:b=b[0];for(c in b)this[c]=b[c];return this};for(b in a=a)(function(c){a[b]=function(){return c.apply(this,arguments),this}})(a[b])}(window.Element.prototype);