Xaralabos Nikolaidhs Xaralabos Nikolaidhs - 6 months ago 11
HTML Question

how to return the text of a option inside a optgroup?

ok, so this is the code

<select name="book" id="book">
<optgroup label="Camus">
<option>The Outsider</option>
<option>The Rebel</option>
<option>The Plague</option>
</optgroup>
<optgroup label="Orwell">
<option>Animal Farm</option>
<option>Nineteen Eighty-Four</option>
<option>Down and Out in Paris and London</option>
</optgroup>
</select>


and i want to have a var to take the text of the second option of the first optgroup (which in this case it is "The Rebel")
lets say i have
var x = document.getElementById("book")......
what i need to put on the rest of the var to get the value i want?
(Javascript only)

Answer

If you wanted to access "The Rebel", just reference the second option within your existing <select> element using the options property:

// Reference the second option in your element to retrieve "The Rebel"
var theRebel = document.getElementById("book").options[1].value;

The options will ignore any optgroups and simply return all of the inner option elements that are available. If you wanted to actually use the available optgroups, you might consider using the document.querySelector() function that allows for a bit more querying flexability :

// Get the first <option> from the first <optgroup> (i.e. "The Outsider")
document.querySelector('#book optgroup:nth-child(1) option:nth-child(1)').value
// Get the first <option> from the second <optgroup> (i.e. "Animal Farm")
document.querySelector('#book optgroup:nth-child(2) option:nth-child(1)').value

Example

var x = document.getElementById("book");
alert(x.options[1].value);
<select name="book" id="book">
  <optgroup label="Camus">
    <option>The Outsider</option>
    <option>The Rebel</option>
    <option>The Plague</option>
  </optgroup>
  <optgroup label="Orwell">
    <option>Animal Farm</option>
    <option>Nineteen Eighty-Four</option>
    <option>Down and Out in Paris and London</option>
  </optgroup>
</select>

Comments