Is there a standard way to get HTMLSelectElement from HTMLOptionElement?

52 views Asked by At

HTMLSelectElement currently provides HTMLSelectElement.options property to access all its options children regardless of optgroup in the way. But, the reverse is not known.

Currently, we need to traverse the element.

let select;
let parent = target;
while (parent.parentElement) {
    if (parent.tagName === 'SELECT') {
        select = parent;
        break;
    }
    parent = parent.parentElement;
}

Is there a standard property or function to get HTMLSelectElement from HTMLOptionElement? Or alternatively more efficient way apart from above code?

1

There are 1 answers

0
Quentin On BEST ANSWER

There's no property of HTMLOptionElement objects which gives you the associated select element.

The closest method is a built-in method for searching the DOM in the manor that you have reimplemented though.

Note that an option element can belong to a select or to a datalist, so you might want to handle both possibilities in your search.

const control = option.closest('select, datalist')