Removing dynamically created child nodes from a form with js / jQuery?
The below post was hugely helpful for what I'm trying to do: Builing a cart with multiple items and the PayPal button in PHP
This part works beautifully:
var inp1 = document.createElement("input");
inp1.setAttribute("type", "hidden");
inp1.setAttribute("id", "item_number_" + current_item);
inp1.setAttribute("name", "item_number_" + current_item);
inp1.setAttribute("value", current_item);
document.getElementById("paypal-form").appendChild(inp1);
but I'm getting a bit stuck on how to remove an item when needed... I am looking for somethi开发者_JS百科ng like:
document.getElementById('payPalForm').removeChild(inp1);
But obviously I need a way to specify/track those dynamically created id's... or is there an easier way I'm missing?
Any help would be appreciated.
use the parentNode property to retrieve the parent element of an element, and use the removeChild method of the parent:
inp1.parentNode.removeChild (inp1);
Reference: parentNode property
I'm not sure where this code belongs, but it would be helpful to encapsulate this within a class.
function NewClass() {
var formPP = document.getElementById('payPalForm');
var lInputs = [];
this.addItem = function(val) {
var inp1 = document.createElement("input");
inp1.setAttribute("type", "hidden");
inp1.setAttribute("id", "item_number_" + val);
inp1.setAttribute("name", "item_number_" + val);
inp1.setAttribute("value", val);
formPP.appendChild(inp1);
lInputs.push(inp1);
}
this.removeItem = function(val) {
var e = formPP.firstChild;
while( e ) {
var eNext = e.nextSibling;
if( e.value == val )
formPP.removeChild(e);
e = eNext;
}
}
}
You'll have to tailor this to meet your needs, but hopefully this gives you a start.
精彩评论