slk500
slk500

Reputation: 781

JS remove last child?

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 its child, but the parent goes away first.

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

Upvotes: 27

Views: 83453

Answers (1)

Miguel
Miguel

Reputation: 20633

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

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

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

Upvotes: 59

Related Questions