How to make a JS framework like jQuery

1425 views javascript
5

?How do I make my own JavaScript library/framework? I want to make it like jQuery so that it's easy to manipulate DOM elements, but I don't see how I can make that... This is how I would have done it:

var $ = document;

but how can I get rid of the 'querySelector', to make it just $('.#elements');??

And honestly I would prefer to use const instead of var, because we don't want anyone to be able to change the definition of $.

answered question

1 Answer

5

This is easy with:

const $ = function(selector) {//or any other name instead of '$'
  if (!(this instanceof $)) {
    return new $(selector);
  };
  this.el = document.querySelectorAll(selector);
};

$.prototype.css = function(notation) {//To make a '.css()'-function
  this.el.forEach(function(element) {
    element.style[Object.keys(notation)[0]] = Object.values(notation)[0];
  });
};
$.prototype.click = function(callback) {//To make a '.click'-function
  this.el.forEach(function(element) {
    element.addEventListener('click', callback, false);
  });
};

And of course you can add even more things here.

posted this

Have an answer?

JD

Please login first before posting an answer.