この解答例はChatGPTによって生成されています,正しいかは自己判断で。 皆の投稿からも解答例が見つかるかもしれませんよ。
BFE.devでのAI解答例 - JavaScript コーディング問題
118. Virtual DOM II - createElement
解法例:
function createElement(type, props, ...children) { return { type, props: { ...props, children: children.map(child => typeof child === "object" ? child : { type: "TEXT", props: { nodeValue: child }, } ), }, };}function render(vDOM) { const { type, props } = vDOM; if (type === "TEXT") { return document.createTextNode(props.nodeValue); } const el = document.createElement(type); for (const [attr, value] of Object.entries(props)) { if (attr === "children") { for (const child of value) { el.appendChild(render(child)); } } else { el.setAttribute(attr, value); } } document.body.appendChild(el);}
この解法例では、createElement() はJSXを想定し、1つ目の引数にはHTMLタグ名しか使わないことを想定しています。また、子要素がTextNodeの場合はtype: "TEXT"のpropを作成します。render() では再帰的にDOM要素を生成しながら子要素に進んでいき、propsではなくsetAttribute()を用いて属性を設定します。最終的に document.body.appendChild()することでDOMが生成されます。