Skip to content

Instantly share code, notes, and snippets.

@kotarok
Created January 23, 2017 13:06
Show Gist options
  • Save kotarok/4d6df4f8ba5834644576f87074197276 to your computer and use it in GitHub Desktop.
Save kotarok/4d6df4f8ba5834644576f87074197276 to your computer and use it in GitHub Desktop.
Array based tiny jQuery subset alternative with minimum number of methods.
var pq = function(q, f) {
return new pq.Obj(q);
};
pq.Obj = function(q) {
if (typeof q === 'string') {
return this.find(q);
} else if (q instanceof pq.Obj) {
return q;
} else if (q instanceof HTMLElement) {
return this.push(q);
}
};
pq.Obj.prototype = [];
pq.Obj.prototype.find = function(q) {
[].forEach.call(document.querySelectorAll(q),function(el){
this.push(el);
}.bind(this));
return this;
};
pq.Obj.prototype.classList = function() {
var args = [].slice.call(arguments);
var m = args.shift();
this.forEach(function(el) {
el.classList[m].apply(el.classList, args);
});
return this;
};
pq.Obj.prototype.on =
pq.Obj.prototype.addEventListener = function(e, f) {
var that = this;
this.forEach(function(el) {
el.addEventListener(e, f.bind(el));
});
return this;
};
pq.Obj.prototype.off =
pq.Obj.prototype.removeEventListener = function(e, f) {
var that = this;
this.forEach(function(el) {
el.removeEventListener(e, f.bind(el));
});
return this;
};
pq.Obj.prototype.val = function(value) {
if (value !== undefined) {
this.forEach(function(el) {
el.value = value;
});
return this;
} else {
var firstItem = this[0];
if (firstItem.value) {
return firstItem.value;
}
}
};
pq.Obj.prototype.remove = function() {
this.forEach(function(el) {
if (!el.remove && el.parentNode) {
el.parentNode.removeChild(el);
} else {
el.remove();
}
});
return this;
};
var pq=function(a,b){return new pq.Obj(a)};pq.Obj=function(a){return"string"==typeof a?this.find(a):a instanceof pq.Obj?a:a instanceof HTMLElement?this.push(a):void 0},pq.Obj.prototype=[],pq.Obj.prototype.find=function(a){return[].forEach.call(document.querySelectorAll(a),function(a){this.push(a)}.bind(this)),this},pq.Obj.prototype.classList=function(){var a=[].slice.call(arguments),b=a.shift();return this.forEach(function(c){c.classList[b].apply(c.classList,a)}),this},pq.Obj.prototype.on=pq.Obj.prototype.addEventListener=function(a,b){return this.forEach(function(c){c.addEventListener(a,b.bind(c))}),this},pq.Obj.prototype.off=pq.Obj.prototype.removeEventListener=function(a,b){return this.forEach(function(c){c.removeEventListener(a,b.bind(c))}),this},pq.Obj.prototype.val=function(a){if(void 0!==a)return this.forEach(function(b){b.value=a}),this;var b=this[0];return b.value?b.value:void 0},pq.Obj.prototype.remove=function(){return this.forEach(function(a){!a.remove&&a.parentNode?a.parentNode.removeChild(a):a.remove()}),this};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment