Removing two children and its parent with Javascript
Been struggling with this one I have the following DOM Structure:
<ol id="add_images">
<li>
<input type="file" /><input type="button" name="removeButton" />
</li>
<li>
<input type="file" /><input type="button" name="removeButton" />
</li>
<li>
<input type="file" /><input type="button" name="removeButton" />
</li>
Basically I'm trying to remove all children and the containing parent (the li tag) when clicking the remove button.
I have tried every manner of parentNode and removeChild combinations. With the below javascript, I can only get to the children but not the parent.
function addFile(addFileButton) {
var form = document.getElementById('add_images');
var li = form.appendChild(document.createElement("li"));
//add additional input fields should the user want to upload additional images.
var f = li.appendChild(document.createElement("input"));
f.className="input";
f.type="file";
f.name="files[]";
//add a remove field button should the user change their mind
var rb = li.appendChild(document.createElement("input"));
rb.type="button";
rb.value="Remove File";
rb.onc开发者_JS百科lick = function () {//This is where the problem is
li.removeChild(this.parentNode);
li.removeChild(this);
}
}
I'm sure its something simple. Thanks for any help.
Since you're trying to remove the <li>
, you need to do it from its parentNode, the ol
.
li.parentNode.removeChild(this.parentNode);
You could also use the form
variable that is already a reference to the ol
.
form.removeChild(this.parentNode);
or:
form.removeChild(li);
Or you could do it all without the variables in order to avoid creating a closure.
this.parentNode.parentNode.removeChild(this.parentNode);
精彩评论