Home » Javascript » Get dropdown option element by display text

Get dropdown option element by display text

Posted by: admin August 19, 2018 Leave a comment

Questions:

I’ve currently been selecting dropdown elements by using:

$('#dropdownId option[value="value"]')

because most of my elements have been written as

<option value="value">value</option>

However, now I’ve come across some elements in this project that do not have the value attribute and instead look like

<option>value</option>

Now I’m struggling to select it using the same syntax that I used prior. I’d like to get the element (not just change the selection) using the same style as before, because it’s a format that’s used dynamically throughout the project. I’ve tried these so far:

$('#dropdownId option[value="value"]'); // doesn't work, I'd assume because it doesn't have a value attribute
$('#dropdownId option[text="value"]'); // Doesn't work, I'd assume because "text" isn't actually an attribute
$('#dropdownId option[label="value"]'); // Doesn't work, I'd assume because even though the value is used as the display text, it's not actually specified in the attributes.

I can’t add a value=”value” to the object, I don’t have control over the html.

Edit: I realize that WebdriverIO, while it uses selectors similar to jQuery, doesn’t necessarily have all of the same functionality. Nathan Hinchey’s seems to work for normal jQuery though.

Answers: