Created
June 8, 2018 20:45
-
-
Save ryandabler/e0916a9454aa42af28c05a981df6d28e to your computer and use it in GitHub Desktop.
This is a jQuery-lite implementation using Symbol.iterator for built-in iterability
This file contains hidden or 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; | |
} | |
splice(...args) { | |
return [ ...this ].splice(...args); | |
} | |
addClass(className) { | |
for (const elem of this) { | |
elem.classList.add(className); | |
} | |
return $$([ ...this ]); | |
} | |
append(content) { | |
for (const elem of this) { | |
elem.append(content.cloneNode()); | |
} | |
return $$([ ...this ]); | |
} | |
attr(name, val) { | |
for (const elem of this) { | |
elem.setAttribute(name, val); | |
} | |
return $$([ ...this ]); | |
} | |
on(event, handler) { | |
for (const elem of this) { | |
elem.addEventListener(event, handler); | |
} | |
return $$([ ...this ]); | |
} | |
[Symbol.iterator]() { | |
let i = 0; | |
const _this = this; | |
return { | |
next() { | |
return _this[i] | |
? { done: false, value: _this[i++] } | |
: { done: true }; | |
} | |
} | |
} | |
} | |
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