JS如何删除最后一个子元素?

24

当我添加一些<select>例如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);
}
1个回答

55

由于您正在添加新元素,如果您想从最新的元素开始删除它们,您需要使用lastChild来获取最后一个元素。

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

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


select.lastChild.parentNode 不总是等于 select 吗? - Dan D.
10
如果想避免文本节点,可以使用 lastElementChild - dakab

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接