441

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" />
DavidRR
  • 18,291
  • 25
  • 109
  • 191
John
  • 32,403
  • 80
  • 251
  • 422

4 Answers4

661

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

TylerH
  • 20,799
  • 66
  • 75
  • 101
raina77ow
  • 103,633
  • 15
  • 192
  • 229
105

For concatenating it's:

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

And for taking union it's:

input[name="Sex"], input[value="M"] {}
eebbesen
  • 5,070
  • 8
  • 48
  • 70
Yogesh Khater
  • 1,690
  • 1
  • 15
  • 20
  • 4
    With `:is()` pseudo-class, you can reduce duplication with the union: `input:is([name="Sex"],[value="M"])` – Ryan May 22 '22 at 01:15
37

Concatenate the attribute selectors:

input[name="Sex"][value="M"]
Dennis
  • 32,200
  • 11
  • 64
  • 79
  • 2
    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 May 22 '18 at 20:50
  • 1
    @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. https://mothereff.in/unquoted-attributes – Dennis Jul 14 '18 at 01:53
  • 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 Jul 17 '18 at 15:31
  • @stevec brackets are invalid in unquoted attributes for that exact reason. This example works in Firefox and Chrome: https://jsfiddle.net/o2abekdh/3/ – Dennis Aug 19 '18 at 01:42
7

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

The following will trigger every td with an attribute named attr

td[attr] 

The following will trigger every elements inside a td with an attribute named attr (not the td itself)

td [attr] 
Mattew Eon
  • 1,722
  • 1
  • 21
  • 38