Selenium Select Object selectByIndex method examines index attribute instead of counting. Why? Selenium Select Object selectByIndex method examines index attribute instead of counting. Why? selenium selenium

Selenium Select Object selectByIndex method examines index attribute instead of counting. Why?


Select the option at the given index. This is done by examing the "index" attribute of an element, and not merely by counting.

I believe this is done to overcome the possibility of Nested Options or OPTGROUP in the Select Dropdown tag. Consider the below Select tag:

<SELECT name="ComOS">  <OPTION selected label="none" value="none">None</OPTION>  <OPTGROUP label="PortMaster 3">    <OPTION label="3.7.1" value="pm3_3.7.1">PortMaster 3 with ComOS 3.7.1</OPTION>    <OPTION label="3.7" value="pm3_3.7">PortMaster 3 with ComOS 3.7</OPTION>    <OPTION label="3.5" value="pm3_3.5">PortMaster 3 with ComOS 3.5</OPTION>  </OPTGROUP>  <OPTGROUP label="PortMaster 2">    <OPTION label="3.7" value="pm2_3.7">PortMaster 2 with ComOS 3.7</OPTION>    <OPTION label="3.5" value="pm2_3.5">PortMaster 2 with ComOS 3.5</OPTION>  </OPTGROUP>  <OPTGROUP label="IRX">    <OPTION label="3.7R" value="IRX_3.7R">IRX with ComOS 3.7R</OPTION>    <OPTION label="3.5R" value="IRX_3.5R">IRX with ComOS 3.5R</OPTION>  </OPTGROUP></SELECT>

In this Select tag, merely counting the index and find the element is not enough as it may return multiple indexes and give error/exceptions.

Moreover, if multiple option tags are found it should be notified also. Hence, 'probably' this may be the reason for examining the "index" attribute before actually returning the element.

In your case, it is better to overload the method and go by indexes as selectByIndex is bound to get slow for huge amount of options tags.

Edit:

Editing after reading the comments. The statement for (WebElement option : getOptions()) is actually slowing the code(Question mostly focus on increasing the speed). So, it really do not matter if the solutions is done by examining the index attribute or other way as that is not the reason for slow speed.

Also, examining the index attribute is helpful for nested options as it indexes the options as the child of Select, and not only as immediate child of Select.