Tengo este código de geeksforgeeks que modifiqué. El código original agregaría y eliminaría de una lista de áreas de texto. Traté de hacer lo mismo con las listas desplegables. Pero, no funciona como se esperaba. Los cambios que me gustaría hacer son:
Aquí está el enlace a mi código actual: https://jsfiddle.net/coderr/dq12vL4j/
HTML
<ul id="list"></ul> <input type="text" id="candidate" /> <button onclick="addItem()" class="buttonClass"> Add item</button> <button onclick="removeItem()" class="buttonClass"> Remove item</button>JavaScript
var myParent = document.body; //Create array of options to be added var array = ["Volvo","Saab","Mercades","Audi"]; //Create and append select list function addItem() { var selectList = document.createElement("select"); selectList.id = "mySelect"; myParent.appendChild(selectList); //Create and append the options for (var i = 0; i < array.length; i++) { var option = document.createElement("option"); option.value = array[i]; option.text = array[i]; selectList.appendChild(option); } } // Creating a function to remove item from list function removeItem() { // Declaring a variable to get select element var a = document.getElementById("list"); var candidate = document.getElementById("candidate"); var item = document.getElementById(candidate.value); a.removeChild(item); }¡Gracias!
Cambió la función removeItem() para que ahora elimine el último hijo del div que contiene todas las listas desplegables. También se agregó una display: block; al div a
const list = document.getElementById('list') var myParent = document.body //Create array of options to be added var array = ['Volvo', 'Saab', 'Mercades', 'Audi'] //Create and append select list function addItem() { var selectList = document.createElement('select') selectList.id = 'mySelect' selectList.style.display = 'block' myParent.appendChild(selectList) //Create and append the options for (var i = 0; i < array.length; i++) { var option = document.createElement('option') option.value = array[i] option.text = array[i] selectList.appendChild(option) } list.appendChild(selectList) } // Creating a function to remove item from list function removeItem() { list.lastChild?.remove() } <input type="text" id="candidate" /> <button onclick="addItem()" class="buttonClass">Add item</button> <button onclick="removeItem()" class="buttonClass">Remove item</button> <div id="list"></div>