2016-09-17 7 views
-1

여기 몇 가지 옵션 요소가 있습니다. 그 중 하나는 값 apple을 보유하고 있습니다. 값 app를 보유하는 option 요소의 id를 가져 오려고합니다. 다음은 다음을 수행했습니다. 나누었다는해당 값을 통해 특정 옵션 요소의 ID를 얻으십시오

<!DOCTYPE html> 
<html> 
<body> 

<form> 
Select a fruit: 
<br> 
<select id="mySelect" size="4"> 
    <option id='for_apple'>Apple</option> 
    <option>Pear</option> 
    <option>Banana</option> 
    <option>Orange</option> 
</select> 
</form> 
<br> 

<button onclick="myFunction()">Remove selected fruit</button> 

<script> 
function myFunction() { 
    var str="Apple"; 
    var x = document.getElementById("mySelect"); 
    if(x[x.selectedIndex].value == str){ 
     alert((x[x.selectedIndex].value).parentElement.id); 
    } 
} 
</script> 

</body> 
</html> 

답변

1

부모 요소 바로 select 요소 자체 일 것이다 텍스트 노드의 부모 요소를 얻을 수 없다?

당신은 당신의 코드에 이미 부모 요소가

if(x[x.selectedIndex].value == str){ 
    alert((x[x.selectedIndex].value).parentElement.id); 
} 

alert(x[x.selectedIndex].id); 
0

로 교체 한 후

특정 옵션의 ID를 알려하려는 경우, 즉 var x = document.getElementById("mySelect"); 및 방법 당신은 <option> 요소의 부모가 올바르지 않다면 alert(element[index].parentElement);으로 할 수 있습니다. element은 HTML <select> 요소이지만 요소 및 parentElement가 모두 동일한 요소를 가리키기 때문에 필요하지 않습니다.

이렇게 할 수 있습니다.

function removeSelectedFruit() { 
 
    var value = 'Apple'; 
 
    var element = document.getElementById("fruits"); 
 
    var index = element.selectedIndex; 
 
    if (index === -1) { 
 
    \t return; 
 
    } 
 
    
 
    if (element.options[index].value === value) { 
 
     alert(element.options[index].id); 
 
     // or as gurvinder372 suggests alert(element[index].id); 
 
     element.remove(index); 
 
    } 
 
}
<div> 
 
    <h2>Select A Fruit</h2> 
 
    <form> 
 
    <select id="fruits" size="4"> 
 
     <option id='for_apple'>Apple</option> 
 
     <option>Pear</option> 
 
     <option>Banana</option> 
 
     <option>Orange</option> 
 
    </select> 
 
    </form> 
 
</div> 
 

 
<div> 
 
    <button onclick="removeSelectedFruit()">Remove Selected Fruit</button> 
 
</div>