Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

That's what I did! I saw a lot of people recommending doing basically:

    const $ = sel => [...document.querySelectorAll(sel)];
But then you get to it and are adding a lot of classes, so you might add a couple of helper methods:

    const addClass = (col, cls) => col.forEach(el => el.classList.add(cls));
    const removeClass = (col, cls) => col.forEach(el => el.classList.remove(cls));

    addClass($('ul li'), 'list-item');
Oh and you might need to inject content before/after, that's a bit trickier but thanks to the classic You Might Not Need jQuery[1] we know how to do it:

    const insertBefore = (col, html) => col.forEach(el => el.insertAdjacentElement('beforebegin', html));
    const insertAfter = (col, html) => col.forEach(el => el.insertAdjacentElement('afterend', html));

    insertAfter($('ul li:last-child'), 'New todo item');
Keep going a bit like that, until you realize you are basically reinventing jQuery but pretty badly, undocumented, and untested.

Add a couple of very nice-to-haves, like chaining (instead of nesting in these examples above) and prototypes and that's what Umbrella JS is, very thin methods to manipulate the DOM and handle events. In fact, compare our "addClass" implementation in this comment to Umbrella's addClass[2], it's almost the same size but hundred times more flexible:

    // Add class(es) to the matched nodes
    u.prototype.addClass = function () {
      return this.eacharg(arguments, function (el, name) {
        el.classList.add(name);
      });
    };

[1] https://youmightnotneedjquery.com/

[2] https://github.com/franciscop/umbrella/blob/master/src/plugi...



Behold my jQuery replacement:

    export function each(qs, cb) {
      if (typeof qs === "string") {
        qs = document.querySelectorAll(qs);
      }
      if (!qs) {
        return;
      }
      if (qs.length === undefined) {
        qs = [qs];
      }
      for (var i = 0; i < qs.length; i++) {
        cb(qs[i], i);
      }
    }

    export function on(ev, qs, cb) {
      let cancelFns = [];

      each(qs, (el) => {
        el.addEventListener(ev, cb);
        cancelFns.push(() => {
          el.removeEventListener(ev, cb);
        });
      });
      return () => {
        cancelFns.forEach((fn) => {
          fn();
        });
      };
    }


That's much worse than jQuery's implementation, there's no event delegation or namespacing

https://api.jquery.com/on/#event-names

https://api.jquery.com/on/#direct-and-delegated-events




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: