Skip to content

Instantly share code, notes, and snippets.

@selvagsz
Last active June 9, 2016 04:02
Show Gist options
  • Save selvagsz/9fe7a09e4ed6a16f00e0f66216c976fd to your computer and use it in GitHub Desktop.
Save selvagsz/9fe7a09e4ed6a16f00e0f66216c976fd to your computer and use it in GitHub Desktop.
There might be a case where you cant offer to include jquery in your project and meanwhile you cant live without its syntactic sugar & less verbosity at least for its basic functionalities
var $ = function(selector) {
if (!(this instanceof $)) {
return new $(selector);
}
this.push(...Array.prototype.slice.apply(document.querySelectorAll(selector)));
return this;
}
// Array-like
$.prototype = {
length: 0,
splice: Array.prototype.splice,
push: Array.prototype.push,
pop: Array.prototype.pop
};
$.prototype.addClass = function(className) {
this.each(function(element) {
element.classList.add(className);
});
return this;
}
$.prototype.removeClass = function(className) {
this.each(function(element) {
element.classList.remove(className);
});
return this;
}
$.prototype.toggleClass = function(className) {
this.each(function(element) {
element.classList.toggle(className);
});
return this;
}
$.prototype.each = function(iteratee, callback) {
var index;
if (Array.isArray(iteratee)) { //TODO: should check for array-like
for (index=0, length=iteratee.length; index<length; index++) {
callback.call(iteratee[index], index, iteratee[index]);
}
} else {
for (index in iteratee) {
callback.call(iteratee[index], index, iteratee[index]);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment