Classe Component
export class Component {
#element = null
constructor(tag, parent, options) {
this.tag = tag
this.parent = parent
this.options = options
this.build()
}
getElement() {
return this.#element
}
build() {
this.#element = document.createElement(this.tag)
Object.assign(this.#element, this.options)
return this
}
render() {
if (this.parent instanceof Component) {
this.parent.getElement().append(this.#element)
} else {
document.querySelector(this.parent).append(this.#element)
}
}
}
Classe Input
import { Component } from "./Component.js";
export class Input extends Component {
constructor(parent, options) {
super('input', parent, options)
}
}
Classe Label
import { Component } from "./Component.js";
export class Label extends Component {
constructor(text, parent, options) {
super('label', parent, Object.assign({}, options, { textContent: text }))
}
}
Classe Form
import { Component } from "./Component.js";
export class Form extends Component {
constructor(parent, options) {
super('form', parent, options)
}
addChildren(...children) {
children.forEach(child => {
this.getElement().appendChild(child.getElement())
})
}
}
Arquivos index.js e index.html para testes
import { Component } from "./Component.js"
import { Form } from "./Form.js"
import { Input } from "./Input.js"
import { Label } from "./Label.js"
const el = new Component('h1', 'body', { innerText: 'Olá, Mundo!' })
console.log(el)
el.tag = 'h2'
el.build().render()
const form = new Form('body')
const label = new Label('Nome:', form, { htmlFor: 'nameInput' })
const input = new Input(form, { id: 'nameInput', name: 'birthday' })
form.render()
label.render()
form.addChildren(input)
form.addChildren(
new Component('br'),
new Component('br'),
new Label('Data de Nascimento:', { htmlFor: 'birthdayInput'}),
new Input(form, { id: 'birthdayInput', name: 'birthday', type: 'date' })
)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="index.js" type="module"></script>
</head>
<body>
</body>
</html>