Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@antonagestam
Last active February 19, 2019 09:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save antonagestam/f8ff54df1bc94839b35bc4d44e92e27e to your computer and use it in GitHub Desktop.
Save antonagestam/f8ff54df1bc94839b35bc4d44e92e27e to your computer and use it in GitHub Desktop.
Wrapper around NodeList to easily implement a jQuery-like API in a minimal way
<script type="module">
import $ from './dollar.js';
$('a').on('click', (e) => {
e.preventDefault();
console.log(e.currentTarget);
alert('ello');
});
</script>
export default (function () {
class $NodeList {
constructor (node_list) {
this.node_list = node_list;
}
on (event_name, event_handler) {
// Attach an event listener to each node of the NodeList
for (let node of this)
node.addEventListener(event_name, event_handler);
return this;
}
[Symbol.iterator] () {
return this.node_list[Symbol.iterator]();
}
first () {
return this.get(0);
}
get (index) {
return this.node_list[index];
}
}
return (selector) => {
if (selector === document)
return new $NodeList([document]);
return new $NodeList(document.querySelectorAll(selector));
}
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment