Skip to content

Instantly share code, notes, and snippets.

@C-Rodg
Last active October 9, 2017 17:46
Show Gist options
  • Save C-Rodg/07d8ac06528f10f2162b83eb1532c48a to your computer and use it in GitHub Desktop.
Save C-Rodg/07d8ac06528f10f2162b83eb1532c48a to your computer and use it in GitHub Desktop.
A small micro-library that shows how libraries like jQuery are made.
const get = (selector, context) => {
// Select the items to manipulate
const GetNodes = function() {
this.nodes = context ? context.querySelectorAll(selector) : document.querySelectorAll(selector);
};
// Add new class to nodes
GetNodes.prototype.addClass = function(className) {
for (let i = 0, j = this.nodes.length; i < j; i++) {
this.nodes[i].classList.add(className);
}
return this;
};
// Remove class from nodes
GetNodes.prototype.removeClass = function(className) {
for (let i = 0, j = this.nodes.length; i < j; i++) {
this.nodes[i].classList.remove(className);
}
return this;
};
return new GetNodes();
};
const headers = get('h1');
const mainHeadings = get('h2', document.querySelector('main'));
headers.addClass('first-class').addClass('second-class').removeClass('removed-class');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment