I need a CSS selector that selects a <select>
element if it contains an <option>
which contains or equals (both would match my requirements) a specified text. Example HTML:
<select name="foo">
<option value="1">First</option>
<option value="2">Second</option>
</select>
I want the <select>
if it contains for example an option labeled "Second". Something like this:
select[option:contains('Second')]
If there is no way to achieve that with CSS selectors, i'd also accept JQuery or XPath selectors.
Selenium locators are key when dealing with locating elements on a webpage. From the list of locators like ID, Name, Class, Tagname, XPath, CSS selector, etc., one can choose any of these as per their needs and locate the web element on a web page.
Simply right click and click Inspect Element. This will bring up the CSS selectors for that element.
The CSS id Selector The id selector uses the id attribute of an HTML element to select a specific element. The id of an element is unique within a page, so the id selector is used to select one unique element! To select an element with a specific id, write a hash (#) character, followed by the id of the element.
var element = document. querySelector("label[for=email]"); ...or in JavaScript using jQuery: var element = $("label[for=email]");
You can't do this with CSS.
You can either use this jQuery selector (:has()
and :contains()
are not part of CSS):
$("select:has(option:contains('Second'))")
Or this XPath expression:
//select[contains(option, 'Second')]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With