2010-05-17 12 views
0

내가이 선택 태그가 자바 스크립트에서 두 번째를 제외한 모든 옵션을 삭제하는 방법몇 가지 옵션을

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

내가

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

내가 생각을하고 싶지 즉, 두 번째 제외한 모든 옵션을 삭제하려면

그러나이 목록은 모두 삭제되므로 도움이 될 수 있습니다.


감사

답변

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

+0

나는 모든 자식 노드를 제거하는 함수가 있다고 생각하지 않는다. 위의 함수는 모든 노드 유형에서 작동해야합니다. – Nalum

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]);