Created
August 22, 2016 13:53
-
-
Save artdevjs/e8af5fa604cc5d87bbcebb06950950b6 to your computer and use it in GitHub Desktop.
jQuery like DOM class
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
| /** | |
| * jQuery like DOM class | |
| * @class | |
| */ | |
| class DOM { | |
| /** | |
| * create a new array like object of elements | |
| * @constructor | |
| */ | |
| constructor(selector) { | |
| if (!selector || selector === ''){ | |
| throw new Error('You must define a class, id or a tag'); | |
| } | |
| if (typeof selector === 'string') { | |
| const elements = document.querySelectorAll(selector); | |
| Array.from(elements).map((el, i) => this[i] = el); | |
| this.length = elements.length; | |
| } else { | |
| this[0] = selector; | |
| this.length = 1; | |
| } | |
| } | |
| /** | |
| * @param {Function} callback A callback to call on each element | |
| */ | |
| each(callback) { | |
| Array.from(this).map((el, i) => callback.call(el, el, i)); | |
| return this; | |
| } | |
| /** | |
| * Add a class to selected elements | |
| * @param {String} className The class name to add | |
| */ | |
| addClass(className) { | |
| return this.each(function() { | |
| this.classList.add(className); | |
| }); | |
| } | |
| /** | |
| * Remove a class from selected elements | |
| * @param {String} className The class name to remove | |
| */ | |
| removeClass(className) { | |
| return this.each(function() { | |
| this.classList.remove(className); | |
| }); | |
| } | |
| /** | |
| * Toggle class on a selected elements | |
| * @param {String} className The class name to toggle | |
| */ | |
| toggleClass(className) { | |
| return this.each(function() { | |
| this.classList.toggle(className); | |
| }); | |
| } | |
| /** | |
| * Check to see if the element has a class | |
| * (Note: Only checks the first elements if more than one is selected) | |
| * @param {String} className The class name to check | |
| */ | |
| hasClass(className) { | |
| return this[0].classList.contains(className); | |
| } | |
| /** | |
| * Attach an event listener with a callback to the selected elements | |
| * @param {String} event Name of event, eg. "click", "mouseover", etc... | |
| * @param {Function} callback The function to call when the event is triggered | |
| */ | |
| on(event, callback) { | |
| return this.each(function() { | |
| this.addEventListener(event, callback, false); | |
| }); | |
| } | |
| off(event, callback) { | |
| return this.each(function() { | |
| this.removeEventListener(event, callback, false); | |
| }); | |
| } | |
| } | |
| export default selector => new DOM(selector); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment