artdev
8/22/2016 - 1:53 PM

jQuery like DOM class

jQuery like DOM class

/**
 * 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);