Getting OPTION tags of a SELECT tag

Last edited on

Overview

This article demonstrates the possible ways to get the OPTION tags inside of a SELECT tag.

Via HTML_Select.options()

Python:

def main():
    startBrowser("https://www.w3schools.com/TAGS/tryit.asp?filename=tryhtml_option")
 
    select = waitForObject({"tagName": "SELECT", "type": "select-one"})
    options = select.options()
    for i in range(options.length):
        o = options.at(i)
        test.log("Option #%s: %s" % (i, o.text))
test.py

Via object.children

JavaScript:

function main()
{
    startBrowser("https://www.w3schools.com/TAGS/tryit.asp?filename=tryhtml_option");

    select = waitForObject({"tagName": "SELECT", "type": "select-one"});
    test.log("Selected index: " + select.selectedIndex.toString() + ": " + select.selectedOption.toString());

    var options = getSelectOptions(o);
    for (var i = 0; i < options.length; i++) {
        var o = options[i];
        test.log("Option: " + o.text + ", selected: " + o.selected.toString() + ", disabled: " + o.property("disabled").toString());
    }
}

function getSelectOptions(select)
{
    var l = new Array(0);
    var c = object.children(select);
    for (var i = 0; i < c.length; i++) {
        var child = c[i];
        if (child.tagName.toLowerCase() == "option") {
            l.push(child);
        }
    }
    return l;
}
test.js

Via real name and "local occurrence"

Python:

def main():
    startBrowser("https://www.w3schools.com/TAGS/tryit.asp?filename=tryhtml_option")
 
    select_rn = {"tagName": "SELECT", "type": "select-one"}
    occurrence = 0
    while True:
        occurrence += 1
        rn = select_rn + ".OPTION" + str(occurrence)
        if not object.exists(rn):
            break
        o = waitForObject(rn)
        test.log("Option #%s: %s" % (occurrence, o.text))
test.py

Via XPath

Python:

def main():
    startBrowser("https://www.w3schools.com/TAGS/tryit.asp?filename=tryhtml_option")

    select = waitForObject({"tagName": "SELECT", "type": "select-one"})
    test.log("Selected index: " + str(select.selectedIndex) + ": " + select.selectedOption)

    options = get_select_option_objs(select)
    for o in options:
        test.log("Option: " + o.innerText)

def get_select_option_objs(select):
    l = []
    xpath_result = select.evaluateXPath("//option")
    count = xpath_result.snapshotLength
    for i in range(count):
        item = xpath_result.snapshotItem(i)
        l.append(item)
    return l
test.py