Created
June 9, 2018 00:03
-
-
Save ryandabler/083c34eab2009d0a01ff6b3fd8b44fa1 to your computer and use it in GitHub Desktop.
This is a jQuery-lite implementation using generator methods for iterability
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class JQ { | |
constructor(list) { | |
let i = 0; | |
while (list[i] !== undefined) { | |
this[i] = list[i]; | |
i++; | |
} | |
this.length = i; | |
} | |
*generator() { | |
for (let i = 0; i < this.length; i++) { | |
yield this[i]; | |
} | |
} | |
splice(...args) { | |
return [ ...this ].splice(...args); | |
} | |
addClass(className) { | |
const iterable = this.generator(); | |
for (const elem of iterable) { | |
elem.classList.add(className); | |
} | |
return $$([ ...this.generator() ]); | |
} | |
append(content) { | |
const iterable = this.generator(); | |
for (const elem of iterable) { | |
elem.append(content.cloneNode()); | |
} | |
return $$([ ...this.generator() ]); | |
} | |
attr(name, val) { | |
const iterable = this.generator(); | |
for (const elem of iterable) { | |
elem.setAttribute(name, val); | |
} | |
return $$([ ...this.generator() ]); | |
} | |
on(event, handler) { | |
const iterable = this.generator(); | |
for (const elem of iterable) { | |
elem.addEventListener(event, handler); | |
} | |
return $$([ ...this.generator() ]); | |
} | |
} | |
const $$ = input => { | |
if (typeof input === "string") { | |
const nodes = document.querySelectorAll(input); | |
return new JQ(nodes); | |
} | |
return new JQ(input); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment