Javascript JS删除最后一个孩子?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34193751/
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-08-23 16:02:15  来源:igfitidea点击:

JS remove last child?

javascript

提问by slk500

When I add a few of >select> ex. SELECT_country,SELECT_country1, SELECT_country2 I would like to remove them in the order of appearance from the newest one to oldest one. But it is removing from oldest one to newest one. I thought SELECT_country is parent, and i will be deleting his child. But the parent goes away first. How I can change it?

当我添加一些 >select> ex 时。SELECT_country,SELECT_country1, SELECT_country2 我想按照从最新到最旧的出现顺序删除它们。但它正在从最旧的一个移到最新的一个。我以为 SELECT_country 是父母,我将删除他的孩子。但父母先走了。我怎样才能改变它?

var j = 0;

function add_country() {
    j++;
    var select = document.getElementById("SELECT_country");
    var clone = select.cloneNode(true);
    clone.setAttribute("id", "SELECT_country" + j);
    clone.setAttribute("name", "country" + j);
    document.getElementById("DIV_country").appendChild(clone);
}

function remove_country() {
    var select = document.getElementById('SELECT_country');
    select.parentNode.removeChild(select);
}

回答by Miguel Mota

Since you are appending new elements you need to get the last element by using lastChildif you want to remove them from newest to oldest.

由于您要添加新元素,因此您需要使用lastChildif来获取最后一个元素,如果要将它们从最新到最旧删除。

function remove_country() {
  var select = document.getElementById('DIV_country');
  select.removeChild(select.lastChild);
}

JSFiddle Demo: https://jsfiddle.net/rrkroxcb/1/

JSFiddle 演示:https://jsfiddle.net/rrkroxcb/1/