JS delete last child?

When I add some from> select> ex. SELECT_country, SELECT_country1, SELECT_country2 I would like to remove them in order of appearance from the newest to the oldest. But he removes from the oldest to the newest. I thought SELECT_country is the parent and I will remove his child. But the parent leaves first. How can i change this?

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);
}
+4
source share
1 answer

Since you are adding new items, you need to get the last item using lastChildif you want to remove them from the newest to the oldest.

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

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

+11
source

Source: https://habr.com/ru/post/1619298/


All Articles