javascript 如何删除javascript中的附加子元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6149802/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 19:40:13  来源:igfitidea点击:

how to remove the append child element in javascript

javascript

提问by thu

<label id="1" >a</label><label id="2" > b </label>

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

我创建了两个标签。单击标签时div,我会在显示的元素中创建一个元素。现在,div如果再次单击标签,我需要删除创建的元素。

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 divelement is created successfully. But when it is clicked again, the divelement is not removed.

单击标签时,该div元素将成功创建。但是当再次单击时,该div元素不会被删除。

回答by Matt

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

idshave 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 divid, if you want it to have an id (div.id = this.id + "_div").

ids在整个 DOM 中必须是唯一的;在您的示例中,看起来您将拥有具有相同 ID 的标签和 div。div如果您希望它有一个 id ( div.id = this.id + "_div") ,您可以轻松地将一个字符串附加到id 上。

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).

如果您的标签中有多个 div,我的示例将不起作用;在这种情况下,ID 方法将是最好的(或使用选择器库)。

Id's could be approached as follows:

可以按如下方式处理 Id:

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