Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS selectors - how to select 'for' in CSS?

I'm using jQuery validation.

When for is now valid, validator is creating those:

<label class="error" for="username" generated="true">

As all label has got the same class=error can I select with CSS this exact one based on 'for'?

I know how to sort this out with jQuery - but always looking for cleanest, purest way. Any suggestion much appreciated.

Pete

like image 290
Iladarsda Avatar asked Jun 30 '11 13:06

Iladarsda


3 Answers

Using the (CSS2) attribute selector:

.error[for="username"]

This will work in IE8+ and all modern browsers.


IE7's attribute selector is buggy: as explained here, to match for you must use htmlFor.

So, if you need IE7 support, use this:

.error[for="username"], .error[htmlFor="username"]
like image 156
thirtydot Avatar answered Oct 14 '22 18:10

thirtydot


Any attribute can be selected with CSS or jQuery using the [] notation. CSS applies to any XML-like syntax, not just HTML -- it doesn't know (or care) what attributes are "valid" as long as the structure is well-formed.

.error[for='username'] {

}

or for a "starts with"

.error[for^='userprefix'] {

}
like image 35
Michael Edenfield Avatar answered Oct 14 '22 16:10

Michael Edenfield


In the css:

.error[for=username] {
}

In the jQuery

$('.error[for=username]')
like image 36
Alex Pliutau Avatar answered Oct 14 '22 18:10

Alex Pliutau