Selecting a CSS element by attribute(s)

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.

Answers


You were close, it's:

div[data-foo="bar"][data-bar="baz"]

Live example

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.)


Need Your Help

Will be storing a list in redis more efficient than a lot of keys?

redis

Suppose, that I have a lot of (tens millions) of keys like this: A_1, A_2, A_3 etc; B_1, B_2 and so on. Values are all short int numbers. Now I am storing all this keys separately, perfomance is very

How to set the php path when directly run php in command prompt

php mysql linux bash centos

Hi I have configured php from source package and its install in /usr/local/bin/php the version was 5.2 but I have upgraded the PHP using yum repository to 5.4 which is installed in /usr/bin/php

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.