-
Notifications
You must be signed in to change notification settings - Fork 467
Description
Describe the feature you'd like:
Accessing <select> elements by the selected option's text
In my experience using dom-testing-library, I've had no issues accessing and interacting with DOM elements in the ways that a user would, except for <select> elements. Unless a label is associated with <select> elements, they are a headache to access, and even harder to do so in a way the software is used.
I would like to get a conversation started for how we can better support <select> elements moving forward.
Here's an example of a select element that would be difficult to access and use:
<select>
<option value="">State</option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
<option value="AR">Arkansas</option>
</select>The first <option> is commonly used in <select> elements, like a placeholder attribute is used for text inputs. What the user sees is the text value of the first option, but it's not possible to access the <select> element given that text value.
What I have been doing on my projects has been to create a getSelectByText() function, though I would hate to have specific, one-use functions or options added to dom-testing-library.
Maybe a user should be able to select a <select> element by using getByText() using the selector option. I can't think of any really elegant solutions, but would be curious to hear from other users of the project.
Describe alternatives you've considered:
For the time being, I've been using this to access <select> values based on the innerText of the selected option:
function getSelectByText(text) {
const selectElems = document.querySelectorAll('select')
for (let i = 0; i < selectElems.length; i++) {
const selectInstance = selectElems[i]
const selectedText = selectInstance.selectedOptions[0].innerText
if (selectedText === text) return selectInstance
}
throw new Error(`Unable to find a select element with the value: ${text}`)
}