2016-09-17 9 views
-1

ここで私はいくつかのオプション要素を持っています。それらの値appleを保持しています。私は値appleを保持するoption要素のidを取得したいと思います。 .Butは特定のオプション要素の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要素そのものになりますテキストノードの親要素を取得することはできませんか?

あなたがその特定のオプションのIDを通知する場合は、

あなたは既にvar x = document.getElementById("mySelect");つまり、あなたのコード内の親要素と方法を持っている

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

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

を交換してくださいあなたは子供の親にアクセスしようとしている<option>要素は間違っていますあなたはalert(element[index].parentElement);としてそれを行うことができますelementはHTML <select>要素ですが、elementと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>

関連する問題