HTML DOM Select options Collection
Last Updated :
29 Dec, 2021
The Select Options Collection in HTML DOM is used to set or return the collection of all options elements in a Drop-Down list. The elements are presented in a sorted order as they appear in a Source Code.
Syntax:
selectObject.options
Properties:
- length: It is a read-only property that returns a number of option elements in the Drop-Down list.
Methods: The DOM select option collection contains five methods which are given below:
- [index]: It returns the element with the selected index specified in the parameter. It starts from 0 and returns NULL if the index value is out of range.
- item(index): It returns the element of the selected index. The index starts from 0 and returns NULL if the index value is out of range.
- namedItem(id): It returns the element with a given id attribute and returns a NULL value if the specified id is not verified.
- [add(option[,index])]: It is used to add a options value in the collection at a particular index.
- remove(index): It is used to remove the option value at the specified index from the collections.
Example 1: Below HTML code used to return the number of options in a drop-down list.
HTML
<!DOCTYPE html>
< html >
< body >
< center >
< h1 style = "color:green;font-size:39px;" >
GeeksForGeeks
</ h1 >
< h2 >DOM Select Option Collection</ h2 >
< label >Your favourite Food Dish: </ label >
< select id = "dish" >
< option >rajma rice</ option >
< option >Idli sambhar </ option >
< option >Samosa</ option >
< option >Daal rice</ option >
< option > shahi paneer </ option >
</ select >
< br >
< button onclick = "myGeeks()" >Submit</ button >
< p id = "sudo" style = "font-size:20px;color:green;" ></ p >
< script >
function myGeeks() {
var g = document.getElementById(
"dish").options.length;
document.getElementById("sudo")
.innerHTML = "The are " + g
+ " options in the drop-down list";
}
</ script >
</ center >
</ body >
</ html >
|
Output:
Example 2: Below HTML code used to get a value of the options which is at 2nd options.
HTML
<!DOCTYPE html>
< html >
< body >
< center >
< h1 style = "color:green;font-size:39px;" >
GeeksForGeeks
</ h1 >
< h2 >DOM Select Option Collection</ h2 >
< label >Your favourite Food Dish: </ label >
< select id = "dish" >
< option >rajma rice</ option >
< option >Idli sambhar </ option >
< option >Samosa</ option >
< option >Daal rice</ option >
< option > shahi paneer </ option >
</ select >
< br >
< button onclick = "myGeeks()" >Submit</ button >
< p id = "sudo" style = "font-size:20px;color:green;" ></ p >
< script >
function myGeeks() {
var g = document.getElementById(
"dish").options[1].text;
document.getElementById("sudo").innerHTML
= "The second options is :" + g;
}
</ script >
</ center >
</ body >
</ html >
|
Output:
Supported Browsers:
- Google Chrome
- Internet Explorer
- Firefox
- Opera
- Safari
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...