通过其值获取特定选项元素的 id

get id of specific option element through its value

这里我有几个选项 element.One 其中持有值 apple.I 想要获取持有值 apple 的选项元素的 ID。到目前为止我做了 following.But 无法获取文本节点的父元素

<!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>

父元素 将是 select 元素本身,对吗?

如果您想提醒该特定选项的 ID,则

替换

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

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

您的代码中已有父元素,即 var x = document.getElementById("mySelect");,您尝试访问子 <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) {
     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>