LoginSignup
2
0

DOM を生成する便利関数

Last updated at Posted at 2019-09-29

Vanilla JS で DOM を生成したいときに便利な関数を作りました。

定義

h.js
/**
 * @template {keyof HTMLElementTagNameMap} K
 * @param {K} tagName
 * @param {Record<string, any>} options
 * @param {(string | Node)[]} children
 * @returns {HTMLElementTagNameMap[K]}
 */
function h(tagName, options = {}, ...children) {
  const element = document.createElement(tagName);
  element.append(...children);
  return Object.assign(element, options);
}
h.ts
function h<K extends keyof HTMLElementTagNameMap>(
  tagName: K,
  options: Record<string, any> = {},
  ...children: (string | Node)[]
): HTMLElementTagNameMap[K] {
  const element = document.createElement(tagName);
  element.append(...children);
  return Object.assign(element, options);
}

使い方

const hr = h('hr');
const img = h('img', { src: 'image.png', alt: 'イメージ' });
const a = h('a', { href: '/' }, 'TOPへ');

const div = h('div', { className: 'sample' }, img, hr, a);
const records = [
  [ 'Alice', 'alice@example.com' ],
  [ 'Bob', 'bob@example.com' ],
  [ 'Carol', 'carol@example.com' ],
];

h('table', {}, ...records.map(r =>
  h('tr', {}, ...r.map(v =>
    h('td', {}, v)
  ))
));

書き捨てのスクリプトなんかにどうぞ。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0