Creating a jQuery like “$” object

前端 未结 8 1381
伪装坚强ぢ
伪装坚强ぢ 2020-12-08 03:25

My end goal is being able to do something like this:

MyVar(parameter).functionToPerform();

Silly enough, even after reading up on how varia

8条回答
  •  渐次进展
    2020-12-08 04:19

    I've recently worked on an exercise that asked to re-create a JQuery like library using ES6 only.

    From the points above I was able to create the instantiation logic that makes it possible to call methods on selectors e.g class names.

    When the instance of $T is called with a selector a new instance of the $TLib is created on the particular selector which will contain all of the methods that can be used on the selector with the elements in context.

    I've added a couple of methods which are chainable in the example below which allows you to add a CSS class to an element and remove the same class in one call e.g:

    $T('.class-selector').addClass('green').removeClass('green);
    

    For those wanting to bootstrap something similar:

    const $T = (selector) => {
      // returns the HTML elements that match the selector
      const elements = document.querySelectorAll(selector);
      return new $TLib(elements, selector);
    };
    
    class $TLib {
      constructor (elements) {
        this._elements = elements;
      }
    
      addClass (className) {
        this._elements.forEach((element) => element.classList.add(className));
        return this;
      }
    
      removeClass (className) {
        this._elements.forEach((element) => element.classList.remove(className));
        return this;
      }
    
      toggleClass (className) {
        this._elements.forEach((element) => {
          const classList = element.classList;
          (classList.contains(className)) ? classList.remove(className) : classList.add(className);
        });
        return this;
      }
    
    }
    

提交回复
热议问题