Last active
June 9, 2016 04:02
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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