Search code examples
javascriptselectparent

get id of specific option element through its value


Here i have a few option element.One of them holding the value apple.I want to get the id of the option element which holds the value apple .So far i did the following.But can't get the parent element of a text node

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

Solution

  • Parent element will be the select element itself, right?

    If you want to alert id of that specific option, then

    Replace

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

    with

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