From 68116c3b09f25712c939cbf51eba12bb5d71e7a8 Mon Sep 17 00:00:00 2001 From: Victor Westerlund Date: Fri, 13 Sep 2024 11:49:15 +0000 Subject: [PATCH] Replace `HTMLCollection` with `NodeList` (#1) I had some weird notion that `querySelectorAll` would return an `HTMLCollection` and not a `NodeList`. ```js [...document.querySelectorAll()].forEach(element => {}); ``` > Maybe I was doing this for no reason before, since `NodeList` already inherits the Array `forEach()` method... Reviewed-on: https://codeberg.org/vlw/elevent/pulls/1 Co-authored-by: Victor Westerlund Co-committed-by: Victor Westerlund --- README.md | 4 ++-- src/Elevent.mjs | 16 ++++++++-------- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 8d56753..363a0d2 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ new Elevent("click", document.querySelector("#myButton"), () => console.log("But # Examples -## Bind from an HTMLCollection +## Bind from a NodeList ```js new Elevent("click", document.querySelectorAll("button"), (event) => console.log(event)); // console: PointerEvent ``` @@ -43,7 +43,7 @@ elevent.bind(document.querySelector("#bindMe")); ```ts Elevent.constructor( eventType: string | null - target: HTMLCollection | HTMLElement | string | null, + target: NodeList | HTMLElement | string | null, callback: CallableFunction ) ``` diff --git a/src/Elevent.mjs b/src/Elevent.mjs index 78c9d12..b5e7087 100644 --- a/src/Elevent.mjs +++ b/src/Elevent.mjs @@ -10,7 +10,7 @@ export class Elevent { /** * Create a new Elevent instance. * @param {string|null} eventType - * @param {HTMLCollection|HTMLElement|string|null} target Strings will be treated as CSS selectors, null will create a template instance + * @param {NodeList|HTMLElement|string|null} target Strings will be treated as CSS selectors, null will create a template instance * @param {function} callback */ constructor(eventType = null, target = null, callback) { @@ -19,13 +19,13 @@ export class Elevent { if (target) { switch (target.constructor) { - case HTMLCollection: - this.#bindHTMLCollection(target); + case NodeList: + this.#bindNodeList(target); break; case String: this._selector = target; - this.#bindHTMLCollection(document.querySelectorAll(target)); + this.#bindNodeList(document.querySelectorAll(target)); // Automatically bind new DOM elements that match the provided CSS selector string this._observer.observe(document.body, { @@ -57,11 +57,11 @@ export class Elevent { } /** - * Bind all HTMLElements inside an HTMLCollection - * @param {HTMLCollection} collection + * Bind all HTMLElements inside a NodeList + * @param {NodeList} nodeList */ - #bindHTMLCollection(collection) { - [...collection].forEach(element => this.bind(element)); + #bindNodeList(nodeList) { + nodeList.forEach(element => this.bind(element)); } /**