2011-01-06 14 views

Respuesta

44
document.getElementById('id').options.length = 0; 

o

document.getElementById('id').innerHTML = ""; 
+1

+1 para 'document.getElementById ('id'). Options.length = 0;' – epascarello

+0

Sí, 'options.length' funciona desde 1996 y Netscape 2! – bobince

+0

bueno viejo options.length – FreshPro

5
var select = document.getElementById('yourSelectBox'); 

while (select.firstChild) { 
    select.removeChild(select.firstChild); 
} 
+0

Me sale un flash raro en IE6 cuando –

0
<select id="thing"><option>fdsjl</option></select> 
<script> 
var el = document.getElementById('thing'); 
el.innerHTML = ''; 

// or this 

while (el.firstChild) { 
    el.removeChild(el.firstChild) 
} 
</script> 
+0

¿Es seguro el cross-browser de innerHTML? – hungryMind

+1

Yesssssssssssss –

0

Es muy fácil de usar JavaScript y DOM:

while (selectBox.firstChild) 
    selectBox.removeChild(selectBox.firstChild); 
+0

imageDropdownBox.options.length – akshay

+0

sí - como @hunter dijo, options.length = 0 es una buena manera de deshacer todas las opciones (JavaScript Array Access like), y voté su respuesta para eso. Pero lamentablemente no funciona bien en todos los navegadores. Si esperas navegadores más antiguos, entonces el nivel DOM-1-1 es la mejor API. – Guss

0

Ajuste del length a 0 es probablemente la mejor manera, pero se puede también haz esto:

var mySelect = document.getElementById("select"); 
var len = mySelect.length; 
for (var i = 0; i < len; i++) { 
    mySelect.remove(0); 
} 
0

La solución más rápida pude encontrar es el siguiente código (tomado de esta article):

// Fast javascript function to clear all the options in an HTML select element 
// Provide the id of the select element 
// References to the old <select> object will become invalidated! 
// This function returns a reference to the new select object. 
function ClearOptionsFast(id) 
{ 
    var selectObj = document.getElementById(id); 
    var selectParentNode = selectObj.parentNode; 
    var newSelectObj = selectObj.cloneNode(false); // Make a shallow copy 
    selectParentNode.replaceChild(newSelectObj, selectObj); 
    return newSelectObj; 
} 
Cuestiones relacionadas