最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

how to remove the append child element in javascript - Stack Overflow

programmeradmin4浏览0评论
<label id="1" >a</label><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.

<label id="1" >a</label><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.

Share Improve this question edited May 27, 2011 at 9:06 Mateen Ulhaq 27.3k21 gold badges119 silver badges152 bronze badges asked May 27, 2011 at 8:43 thuthu 111 gold badge1 silver badge2 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 3
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)

  1. 暂无评论