[Typescript] Type JQuery
const $: any = {}
/**
* Get the <button> element with the class 'continue'
* and change its HTML to 'Next Step...'
*/
$("button.continue").html("Next Step...")
/**
* Show the #banner-message element that is hidden with visibility:"hidden" in
* its CSS when any button in #button-container is clicked.
*/
const hiddenBox = $("#banner-message")
$("#button-container button").on("click", (event) => {
hiddenBox.show()
})
/**
* Make an API call and fill a <div id="post-info">
* with the response data
*/
$.ajax({
url: "https://jsonplaceholder.typicode.com/posts/33",
success: (result) => {
$("#post-info").html(
"<strong>" + result.title + "</strong>" + result.body
)
},
})
.
.
.
import fetch from "node-fetch";
function isHTMLElement(x: HTMLElement | Element | null): x is HTMLElement {
return x !== null && x instanceof HTMLElement;
}
class SelectorResult {
#elements;
constructor(elements: NodeListOf<Element>) {
this.#elements = elements;
}
html(contents: string) {
this.#elements.forEach((elm) => {
elm.innerHTML = contents;
});
}
on<K extends keyof HTMLElementEventMap>(
arg0: K,
arg1: (event: HTMLElementEventMap[K]) => void
) {
this.#elements.forEach((elm) => {
if (isHTMLElement(elm)) {
elm.addEventListener(arg0, arg1);
}
});
}
show() {
this.#elements.forEach((elm) => {
if (isHTMLElement(elm)) {
elm.style.visibility = "visible";
}
});
}
hide() {
this.#elements.forEach((elm) => {
if (isHTMLElement(elm)) {
elm.style.visibility = "hidden";
}
});
}
}
function $(selector: string) {
return new SelectorResult(document.querySelectorAll(selector));
}
namespace $ {
export function ajax({
url,
success,
}: {
url: string;
success: (data: any) => void;
}) {
return fetch(url)
.then((res) => res.json())
.then((res) => {
success(res);
return res;
})
.catch((err: unknown) => {});
}
}
export default $;