开发者

how to remove the append child element in javascript

开发者 https://www.devze.com 2023-03-08 14:35 出处:网络
<label id=\"1\" >a</labe开发者_StackOverflow中文版l><label id=\"2\" > b </label>
<label id="1" >a</labe开发者_StackOverflow中文版l><label id="2" > b </label>

I have two labels created. When a label is clicked, I create a div element within that I displayed. Now I need to remove the created div element if the label is again clicked.

if (click == 1) {
    var prevWin = document.createElement("div");
    prevWin.id = 1;
    prevWin.innerHTML = outMsg;
    document.body.appendChild(prevWin);
} else {
    var prevWin = document.body.getElementsById(1);
    document.body.removeChild(prevWin);
}

When a label is clicked the div element is created successfully. But when it is clicked again, the div element is not removed.


function labelOnClick () {
    var divs = this.getElementsByTagName("div");

    if (divs.length) {
        divs[0].parentNode.removeChild(divs[0]);
    } else {
        var div = document.createElement("div");
        div.innerHTML = outMsg;

        this.appendChild(div);
    }
}

ids have got to be unique throughout the DOM; in your example, it looks like you'll have the label and the div with the same id. You could easily append a string to the div id, if you want it to have an id (div.id = this.id + "_div").

My example wont work if you have more than one div in your label; in which case the ID approach would be best (or use a selector library).

Id's could be approached as follows:

function labelOnClick () {
    function makeDivId(id) {
        return id + "_div";
    };

    var div = this.getElementById(makeDivId(this.id));

    if (div) {
        div.parentNode.removeChild(div);
    } else {
        div = document.createElement("div");
        div.innerHTML = outMsg;
        div.id = makeDivId(this.id);

        this.appendChild(div);
    }
}
0

精彩评论

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

关注公众号