ChatGPT解决这个技术问题 Extra ChatGPT

Specify multiple attribute selectors in CSS

What is the syntax for doing something like:

input[name="Sex" AND value="M"]

Basically, I want to select the input element that has the attribute name="Sex" as well as the attribute value="M":

<input type="radio" name="Sex" value="M" />

Elements such as the following should not be selected:

<input type="radio" name="Sex" value="F" />

T
TylerH

Simple input[name=Sex][value=M] would do pretty nice. And it's actually well-described in the standard doc:

Multiple attribute selectors can be used to refer to several attributes of an element, or even several times to the same attribute. Here, the selector matches all SPAN elements whose "hello" attribute has exactly the value "Cleveland" and whose "goodbye" attribute has exactly the value "Columbus": span[hello="Cleveland"][goodbye="Columbus"] { color: blue; }

As a side note, using quotation marks around an attribute value is required only if this value is not a valid identifier.

JSFiddle Demo


is there something like this, but OR instead of AND?
You mean other than , (comma)?
you can’t write span[hello="Cleveland"],[goodbye="Columbus"] but you have to repeat a (possibly long) part.
You have to indeed (at least for the moment), unless you use preprocessors. Consult this thread for more details.
Please notice that there shouldn't be space symbols between two [][]
e
eebbesen

For concatenating it's:

input[name="Sex"][value="M"] {}

And for taking union it's:

input[name="Sex"], input[value="M"] {}

With :is() pseudo-class, you can reduce duplication with the union: input:is([name="Sex"],[value="M"])
D
Dennis

Concatenate the attribute selectors:

input[name="Sex"][value="M"]

It's worth noting that at least one of the attribute values must be quoted. This would fail if you wrote it as input[name=Sex][value=M] even though it would be valid to have a selector with only one attribute that didn't use quotes.
@stevec Did you mean to put this on the accepted answer? I've quoted the values in my answer. I also don't think that's true. You need quotes if the answer contains certain characters but not in this example. mothereff.in/unquoted-attributes
I added that note because I tried it in several browsers without quotes and it failed in all. I believe that the issue is that without quotes on at least one, it is ambiguous because it could be interpreted as an input whose name is Sex][value=M
@stevec brackets are invalid in unquoted attributes for that exact reason. This example works in Firefox and Chrome: jsfiddle.net/o2abekdh/3
J
Jean-Philippe Martin

Just to add that there should be no space between the selector and the opening bracket.

td[someclass] 

will work. But

td [someclass] 

will not.