JSFiddle - React, Tailwind, and code Playground
HTML
<h1>Hello, add tags</h1>
<form>
<label for="tag">Tag :</label>
<input type="text" id="tag" name="tag" />
<button>Add Tag</button>
</form>
<hr />
<h3>Tags</h3>
<div class="tags__wrapper">
</div>
JavaScript
class Tag {
constructor(name) {
this.el = null
this.name = name
this.init()
}
init = async () => {
this.el = await this.displayTag()
this.bindEvents()
}
bindEvents = () => {
const removeButton = this.el.querySelector('button')
removeButton.addEventListener('click', this.removeTag)
}
displayTag = () => {
return new Promise(resolve => {
const wrapper = document.querySelector('.tags__wrapper')
const tagEl = document.createElement('div')
tagEl.className = 'tag'
tagEl.dataset.name = this.name
tagEl.innerHTML = `<div class="tag__wrapper">
<b class="tag__name">${this.name}</b>
<button>Delete</button>
</div>`
wrapper.appendChild(tagEl)
resolve(tagEl)
})
}
removeTag = (e) => {
e.preventDefault()
this.el.remove()
delete this
}
}
class Page {
constructor() {
this.tags = []
this.init()
}
init = () => {
this.bindEvents()
}
bindEvents = () => {
const button = document.querySelector("button")
button.addEventListener("click", this.createTag)
}
createTag = (e) => {
e.preventDefault()
const name = document.querySelector("input").value
const tag = new Tag(name)
this.tags.push(tag)
}
}
new Page()