简体   繁体   English

要查找的CSS选择器 <select>与指定<option>标签

[英]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. 我需要一个CSS选择器来选择一个<select>元素,如果它包含一个<option> ,它包含或等于(两者都符合我的要求)指定的文本。 Example HTML: 示例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". 如果它包含例如标记为“Second”的选项,我想要<select> 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. 如果用CSS选择器无法实现这一点,我也会接受JQuery或XPath选择器。

You can't do this with CSS. 你不能用CSS做到这一点。

You can either use this jQuery selector ( :has() and :contains() are not part of CSS): 你可以使用这个jQuery选择器( :has():contains()不是CSS的一部分):

$("select:has(option:contains('Second'))")

Or this XPath expression: 或者这个XPath表达式:

//select[contains(option, 'Second')]
$('select[name="foo"] option:contains("Second")').parent().addClass('selected');

也许这可以帮助

The simplest way to do this is to use the contains() selector on the option 最简单的方法是在选项上使用contains()选择器

$("select option:contains('Second')")

Here's a working example: http://jsfiddle.net/8Tn4Z/ 这是一个有效的例子: http//jsfiddle.net/8Tn4Z/

and a version with the value attribute not included : http://jsfiddle.net/8Tn4Z/1/ 和一个不包含value属性的版本: 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: 要获得实际的select元素本身,您可以在上面的代码中使用parent()方法,以便:

var selectElement = $("select option:contains('Second')").parent();

Here's an example: http://jsfiddle.net/8Tn4Z/2/ 这是一个例子: http//jsfiddle.net/8Tn4Z/2/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM