JSFiddle - React, Tailwind, and code Playground
HTML
<div id="main">
<div class="field"><span>Filed:</span><input name="filed[0]"><span class="add">افزودن</span></div>
</div>
CSS
.field {
margin-bottom: 1em;
}
.field input {
margin: 0 0.5em;
}
.field .add {
color: green;
cursor: pointer;
font-weight: bold;
}
.field .remove {
color: red;
cursor: pointer;
font-weight: bold;
}
JavaScript
let nextFieldId = 1
let removes
const addField = () => {
let divField = document.createElement("div")
divField.setAttribute("class", "field")
let spanName = document.createElement("span")
let spanNameText = document.createTextNode("Field:")
spanName.appendChild(spanNameText)
let input = document.createElement("input")
input.setAttribute("name", "field["+nextFieldId+"]")
let spanRemove = document.createElement("span")
spanRemove.setAttribute("class", "remove")
let spanRemoveText = document.createTextNode("حذف")
spanRemove.appendChild(spanRemoveText)
divField.appendChild(spanName)
divField.appendChild(input)
divField.appendChild(spanRemove)
document.getElementById("main").appendChild(divField)
}
document.querySelector(".field .add").addEventListener("click", function() {
addField()
removes = document.querySelectorAll(".field .remove")
removeInit()
nextFieldId++
})
let removeInit = () => {
Array.from(removes).forEach(remove => {
remove.addEventListener("click", function() {
let parent = this.parentNode
removeNode(parent)
})
})
}
let removeNode = (e) => {
if(e.parentNode != null)
e.parentNode.removeChild(e)
}