CSS selector to find <select> with specified <option> label
I need a CSS selector that selec开发者_开发技巧ts 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.
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')]
$('select[name="foo"] option:contains("Second")').parent().addClass('selected');
Maybe this can help
The simplest way to do this is to use the contains()
selector on the option
$("select option:contains('Second')")
Here's a working example: http://jsfiddle.net/8Tn4Z/
and a version with the value attribute not included : http://jsfiddle.net/8Tn4Z/1/
To get the actual select element itself you can simply use the parent()
method on the above code so that:
var selectElement = $("select option:contains('Second')").parent();
Here's an example: http://jsfiddle.net/8Tn4Z/2/
精彩评论