Reputation: 26124
I've been using CSS3 selectors to select specific elements based on their attributes, although today, I have programmed myself into a corner, where I need a select a specific element based on the presence of TWO different attributes, instead of only 1.
e.g. I need to select the first div.
<div data-foo="bar" data-bar="baz">
<div data-foo="bar" data-bar="lorem">
<div data-foo="ipsum" data-bar="baz">
Just for fun, I tried div[data-foo="bar", data-bar="baz"]
, but not surprisingly, that didn't work.
Is there any way for me to get that specific element?
Right now, the only solution I can think of is to select all elements with the correct data-foo
attribute, and then loop through the results to find the element with the correct data-bar
attribute.
Upvotes: 3
Views: 361
Reputation: 1074038
You were close, it's:
div[data-foo="bar"][data-bar="baz"]
From the CSS 2.1 specification:
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; }
(There's a new CSS3 Selectors spec as well, which is increasingly supported, but we don't need CSS3 features for this.)
Upvotes: 7