2011-01-06 10 views

risposta

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

o

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

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

+0

Sì, 'options.length' funziona fino al 1996 e Netscape 2! – bobince

+0

good old options.length – FreshPro

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

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

Ho uno strano flash in IE6 quando –

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

È innerHTML cross-browser sicuro? – hungryMind

+1

Yesssssssssssss –

0

È molto facile utilizzando JavaScript e DOM:

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

imageDropdownBox.options.length – akshay

+0

sì - come ha detto @hunter, options.length = 0 è un buon modo per annullare l'impostazione di tutte le opzioni (accesso di array Javascript come), e ho votato la sua risposta per quello. Ma sfortunatamente non funziona così bene su tutti i browser. Se ti aspetti che i browser più vecchi, allora io sottolinei DOM-level-1 è la migliore API. – Guss

0

Impostazione del length a 0 è probabilmente il modo migliore, ma è possibile anche fare questo:

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

La soluzione più veloce ho potuto trovare è il seguente codice (tratto da questo 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; 
} 
Problemi correlati