Reputation: 183
I created add
input field and remove
field. The add
input is working fine, but remove
item is not working. Please kindly suggest how to do this. I have attached code. Thanks in advance.
var x = 1;
function addRow() {
var e1 = document.createElement("div");
x++;
// e1.id = "box1";
e1.setAttribute('id', "input_" + x);
e1.className = "box";
var cont = document.getElementById("content")
cont.appendChild(e1);
var e2 = document.createElement("input");
e2.type = "text";
e2.name = "name1";
var cont1 = document.getElementById("input_" + x)
cont1.appendChild(e2);
}
function removeElement() {
// Removes an element from the document
var element = document.getElementById('content');
element.parentNode.removelastChild(element);
}
var rslt = (nodee = document.getElementById(id)).parentNode.removeChild(nodee);
<div id="content">
</div>
<input type="button" value="add" onclick="addRow()">
<input type="button" value="Delete" onclick="removeElement()">
Upvotes: 0
Views: 95
Reputation: 1
you can also try this one. This is alternate solution.
function removeElement() {
var element = document.getElementById('content');
element.removeChild(element.childNodes[0]);
}
Upvotes: 0
Reputation: 16
You can try this, because 'removelastChild' is not an effective method
function removeElement() {
// Removes an element from the document
var element = document.getElementById('content');
var childrens = element.children;
childrens[childrens.length-1].remove()
}
Upvotes: 0
Reputation: 1
I don't think element.removelastChild
is a valid function. You may have to get the last child using
element.lastElementChild
and remove it using
parentnode.removeChild(childnode)
Upvotes: 0
Reputation: 15614
var lastEl = element.lastElementChild;
element.removeChild(lastEl);
Get the last element of a node using lastElementChild then remove it from parent element using removeChild
DEMO
var x = 1;
function addRow() {
var e1 = document.createElement("div");
x++;
// e1.id = "box1";
e1.setAttribute('id', "input_" + x);
e1.className = "box";
var cont = document.getElementById("content")
cont.appendChild(e1);
var e2 = document.createElement("input");
e2.type = "text";
e2.name = "name1";
var cont1 = document.getElementById("input_" + x)
cont1.appendChild(e2);
}
function removeElement() {
// Removes an element from the document
var element = document.getElementById('content');
var lastEl = element.lastElementChild;
element.removeChild(lastEl);
}
<div id="content">
</div>
<input type="button" value="add" onclick="addRow()">
<input type="button" value="Delete" onclick="removeElement()">
Upvotes: 1