简体   繁体   中英

Javascript: How to remove lastChild among select statements

The below code I have is designed to create and remove a new dropdown menu upon clicking the button. However, when clicking the remove button, it removes the first created dropdown. How do I set it up to remove the last created dropdown?

  document.getElementById('add').addEventListener('click', function(addioc){ var addition = document.getElementById('IOC_select').cloneNode(true); document.getElementById('IOC_input').appendChild(addition); } ); document.getElementById('remove').addEventListener('click', function(removeioc){ var subtraction = document.getElementById('IOC_select'); subtraction.parentNode.removeChild(subtraction); } ) 
 <!DOCTYPE html> <html> <body> <form id="IOC_input"> <select id = "IOC_select"> <option value = "IOC"> IOC Type: </option> </select> </form> <button id="add">ADD IOCs</button> <button id="remove"> REMOVE IOCs</button> <button id="submit"> SUBMIT IOCs</button> </body> </html> 

Edited to add the HTML code that was asked for.

document.getElementById('IOC_select'); will always return the first element with id="IOC_select" .
Remove the last element of the subtraction.parentNode.children Change the following part

document.getElementById('remove').addEventListener('click',
        function(removeioc){
            removeioc.preventDefault();
            var subtraction = document.getElementById('IOC_select');
            let children = subtraction.parentNode.children
            subtraction.parentNode.removeChild(children[children.length - 1]);
            return false;
        }
    )

If you use .querySelector() , you can get a direct reference to the last option element by using the last-child pseudo-class and remove it:

Also, you don't need the lines about .preventDefault() since there is no default behavior associated with these events. You also don't need return false here.

 document.getElementById('remove').addEventListener('click', function(){ var subtraction = document.querySelector('#IOC_select > option:last-child'); // If there is an element to remmove if (subtraction){ subtraction.parentNode.removeChild(subtraction); } }); 
 <select id="IOC_select"> <option>choice 1</option> <option>choice 2</option> <option>choice 3</option> <option>choice 4</option> <option>choice 5</option> <option>choice 6</option> <option>choice 7</option> <option>choice 8</option> </select> <button id="remove">Remove last choice</button> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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