So is there an easy way to get the last node so I could simply delete inputs from the last one? deleteinput() function.
<script>
var form = document.getElementById("form");
function newinput(){
var input = document.createElement("input");
input.type = "text";
form.appendChild(input);
}
function deleteinput(){
form.removeChild();
}
</script>
You should add your input
s some id
as well so you can delete them by providing id
as an argument to your deleteinput()
function.
Your function will look like this
function deleteinput(name) {
var input = document.getElementByName(name);
form.removeChild(input);
}
Also newinput()
will change accordingly:
function newinput(name) {
var input = document.createEleement("input");
input.type = "text";
input.name = name;
form.appendChild(input);
}
You can also create some global integer and generate name of input automatically by some string + incremented value of your global variable - this way you don't need to pass name
argument to newinput()
function.
I am not sure that this will 100% work, I did not test it. Maybe you will need to tweak it little bit but the main logic should be correct.
You can use the lastChild
property to get the last child, and the previousSibling
to step through them until you get to an input
function deleteinput() {
for (var child = form.lastChild; child.nodeName.toLowerCase() != 'input'; child = child.previousSibling) {
}
if (child) {
form.deleteChild(child);
}
}
Yes you can get and remove the last element this way.
var ele = document.getElementById("parent element Id").lastChild;
ele.remove();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.