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

时间:2016-09-17 06:53:07

标签: javascript select parent

这里我有一些选项元素。其中一个持有值apple.I想得到包含值apple的选项元素的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>

2 个答案:

答案 0 :(得分:1)

父元素本身就是select元素,对吧?

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

替换

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

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

答案 1 :(得分:0)

您的代码中已经有父元素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>