简体   繁体   English

JS删除最后一个孩子?

[英]JS remove last child?

When I add a few of <select> ex.当我添加一些<select>前。 SELECT_country, SELECT_country1, SELECT_country2 I would like to remove them in the order of appearance from the newest one to oldest one. SELECT_country, SELECT_country1, SELECT_country2我想按照从最新到最旧的出现顺序删除它们。 But it is removing from oldest one to newest one.但它正在从最旧的一个移到最新的一个。 I thought SELECT_country is parent , and I will be deleting its child , but the parent goes away first.我以为SELECT_countryparent ,我将删除它的child ,但parent会先消失。

How I can change it?我怎样才能改变它?

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

Since you are appending new elements you need to get the last element by usinglastChild if you want to remove them from newest to oldest.由于您要添加新元素,lastChild如果要将它们从最新到最旧删除,则需要使用lastChild获取最后一个元素。

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/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM