Skip to content

Instantly share code, notes, and snippets.

@ygkn
Last active August 20, 2023 19:58
Show Gist options
  • Save ygkn/2fe61c327aa3850d33da9785bb852dbb to your computer and use it in GitHub Desktop.
Save ygkn/2fe61c327aa3850d33da9785bb852dbb to your computer and use it in GitHub Desktop.
ラクラクDOM

ラクラクDOM

ユーザースクリプトなどであまりライブラリ使いたくない人へ

createElement

生DOMの要素作るマン

JSX pragma 風味

$, $$

生DOMの要素選択するマン

jQuery 風味

type Child = Node | string | number | boolean | undefined | null;
const createElement = <K extends keyof HTMLElementTagNameMap>(
tagName: K,
{
style,
...attrs
}: Partial<
Omit<HTMLElementTagNameMap[K], "style"> & {
style: Partial<HTMLElementTagNameMap[K]["style"]>;
}
> = {},
...children: Child[]
) => {
const element = document.createElement(tagName);
Object.assign(element, attrs);
Object.assign(element.style, style);
element.append(
...children
.filter(
(child): child is Exclude<Child, undefined | null | boolean> =>
child == null || typeof child === "boolean",
)
.map((child) => (typeof child === "number" ? child.toString() : child)),
);
return element;
};
const $ = (sel: string, doc: HTMLElement | Document = document) =>
doc.querySelector(sel);
const $$ = (sel: string, doc: HTMLElement | Document = document) =>
doc.querySelectorAll(sel);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment