Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS selector to find <select> with specified <option> label

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.

like image 992
Alp Avatar asked Aug 16 '11 16:08

Alp


People also ask

Which selector is used to locate elements based on their tag name?

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.

How do I find the correct CSS selector of an element?

Simply right click and click Inspect Element. This will bring up the CSS selectors for that element.

How do I select specific tags in CSS?

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.

How do I access a label in CSS?

var element = document. querySelector("label[for=email]"); ...or in JavaScript using jQuery: var element = $("label[for=email]");


1 Answers

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')]
like image 128
BoltClock Avatar answered Sep 27 '22 20:09

BoltClock