Wednesday, August 27, 2008

Attribute Selectors

Attribute selectors can be used to select (X)HTML elements based on their attributes and the value of their attributes. An attribute selector is made by enclosing the name of the attribute in square brackets - [ and ]. Example:
To select the following element - <img src="image.gif" alt="product" /> , you can use the following selector - [alt]. This would select any element in the document with the img attribute. To only select img elements that have the alt attribute, you would use the element name with the attribute selector - img[alt] .
You can also specify the exact attribute value - img[alt="button"]. Some attribute values have spaces in them. Such attributes can be selected by their partial attribute value. For example, the following XHTML element - <img src="images/rose.gif" alt="picture of the rose in sunlight" /> can be selected using the following CSS selector - [alt~="rose"] .
The |= operator (the "pipe" character) is used to select elements with an attribute whose value is a hyphenated string beginning with a particular string of text. Example: [src|="image"] will select the following elements <img src="image-1.gif" alt="a rose"> <img src="image-2.gif" alt="a tulip">

CSS3 Attribute Selectors

Using the ^= operator, you can select elements whose attribute values begin with a particular string of text. Example: a[href^="ftp:"] will match all links that refer to FTP sites.
The $= operator will match all elements with a particular attibute whose value ends with a particular string of text. Example: img[src$="gif"] .
The *= operator will match an elements with a particular attribute whose value contains a particular string. Example: img[alt*="rose"] will match <img src="image.jpg" alt="picture of a rose in a vase"> IE6 does not support Attribute Selectors. IE7 does not support stand-alone Attribute Selectors - example: [alt] will not work in IE7 but img[alt] will.

No comments: