开发者

Removing two children and its parent with Javascript

开发者 https://www.devze.com 2023-02-12 20:56 出处:网络
Been struggling with this one I have the following DOM Structure: <ol id=\"add_images\"> <li>

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);
0

精彩评论

暂无评论...
验证码 换一张
取 消