Skip to content

Instantly share code, notes, and snippets.

@renaudtertrais
Created December 28, 2014 21:48
Show Gist options
  • Save renaudtertrais/c73d17940442baa4c92e to your computer and use it in GitHub Desktop.
Save renaudtertrais/c73d17940442baa4c92e to your computer and use it in GitHub Desktop.
Automatize querySelectorAll manipulation.
var t = console.log;
var select = function( selector ){
return new Collection( document.querySelectorAll( selector ) );
};
var Collection = function( collection ){
collection = collection || [];
this.collection = Array.prototype.slice.call(collection);
this.length = this.collection.length;
};
Collection.prototype = {
fn : function(){
var params = Array.prototype.slice.call(arguments);
var method = params.shift();
for(var i=0; elt = this.collection[i] ; i++ ){
elt[method].apply(elt,params);
}
return this;
},
each: function( handler ){
for( var i=0,elt; elt = this.collection[i];i++ ){
handler.call(elt,i);
}
},
nth: function( n ){
if( parseInt(n) == n ){
return this.collection[n];
}else{
var multi=1, add = 0;
if( n === 'even' ){
multi = 2;
}else if( n === 'odd' ){
multi = 0;
}else{
var res = /([0-9]+)n/.exec(n);
if(res) multi = res[1];
res = /\+([0-9]+)/.exec(n);
if(res) add = res[1];
}
var coll = new Collection();
for( var i=0,elt; elt = this.collection[i];i++ ){
if(i>=add){
// odd
if(multi===0 && (i+1)%2 > 0){
coll.collection.push(elt);
// even, 3n ...
}else if( (i+1)%multi === 0){
coll.collection.push(elt);
}
}
}
return coll;
}
}
}
select('li')
//.fn('addEventListener', 'click' , alert.bind(null,'yolo') )
.fn('setAttribute', 'style' , 'cursor:pointer;color:red' )
//.nth(1).setAttribute('style','color:blue');
.nth('3n').fn('setAttribute', 'style' , 'color:blue' )
.each(function(i){t(this.innerHTML,i)});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment