軽量なライブラリで簡単にDOM生成したいという時に便利なdomgenというライブラリを作りました。
DOMを生成する時に document.createElement() や appendChild() で頑張るのは辛いものです。
domgenを使えば簡単に短くDOM生成をするコードを記述できます。
インストール
npm install --save domgen
使い方
import h from 'domgen'
// p要素のDOMを作成
let p = h('p')
// 属性や子要素を指定して作成
let s = h('span', {style: {color: 'orange'}}, 'Text')
// 子要素をもった要素を作成
let ps = h('p', {style: {padding: '20px'}}, [
['span', {style: {color: 'red'}}, 'Text1'],
['br'],
['span', {style: {color: 'blue'}}, 'Text2']
])
// イベントリスナーの指定
let b = h('button', {onclick: () => alert('Click!')}, 'Button')
属性や子要素は型を見てあるていどインテリジェントに対応してくれます。class/style属性は文字列でも指定できますが、配列やオブジェクトでも指定できます。イベントリスナーの設定もサンプルの通り、関数または文字列を受け取ることができます。
上記のサンプルでは h という名前でインポートしていますが、ブラウザでロードする場合はdomgenという名前でglobalスコープに追加されます。
以下はREADME.mdにも記述してあるサンプルをそのまま転載しました。
// simple example
document.body.appendChild(
domgen('p', {style:'color:orange;'}, 'Text')
)
// Natural notation for class and style attributes.
// Ofcourse you can also write like this: class: 'classA classB'
document.body.appendChild(
domgen('p', {class:['classA', 'classB']}, 'Text have class')
)
document.body.appendChild(
domgen('p', {style:{'color': 'green'}}, 'Text have style')
)
// You can set children recursively.
document.body.appendChild(
domgen('p', null, [domgen('span', null, 'Child Element Text Node')])
)
// Array notation
document.body.appendChild(
domgen('p', null, [['span', null, 'Generated by array notation.']])
)
// Event
function onClickButton () {
alert('click!')
}
document.body.appendChild(
domgen('button', {onclick: onClickButton}, 'Click Me')
)