2010-05-17 34 views
0

我有一個選擇的標籤,有些選項如何刪除除第二的所有選項中的JavaScript

<select id="sel"> 
    <option>text1</option> 
    <option>text2</option> 
    <option>text3</option> 
    <option>text4</option> 
</select> 

我想刪除除第二的所有選項,也就是我想

<select id="sel"> 
    <option>text2</option> 
</select> 

我認爲它必須看起來像這樣

document.getElementById('sel').options.length= 0; 

但它刪除所有列表,所以你可以幫我。


感謝

回答

1

你應該能夠修改此做你想要的。

function removeChildrenFromNode(node) 
{ 
    if(node === undefined || node ==== null) 
    { 
     return; 
    } 

    var len = node.childNodes.length; 

    while (node.hasChildNodes()) 
    { 
     node.removeChild(node.firstChild); 
    } 
} 
+0

有什麼功能,刪除所有的孩子的? 我用來寫document.getElementById('sel')。options.length = 0,這是真的嗎? – Simon 2010-05-17 16:41:20

+0

我不認爲有一個功能來刪除所有的子節點,你有什麼工作正常。上面的功能應該適用於所有節點類型。 – Nalum 2010-05-17 17:04:54

2
var 
    sel = document.getElementById("sel"), 
    options = sel.getElementsByTagName("option"); 
for (var i=options.length-1; i>=2; i--) { 
    sel.removeChild(options[i]); 
} 
sel.removeChild(options[0]); 
相關問題