Selecting Elements by Attribute

The attribute selector matches attributes by different aspects of attributes.

The element attribute selector has the following syntax:

 
[condition]
  

or

 
elementType[<condition>]
  

It matches elements by looking at the value of attributes

 
<!DOCTYPE HTML> 
<html> 
    <head> 
        <title>Example</title> 
        <style type="text/css"> 
        [href] { 
            border: thin black solid; 
            padding: 4px; 
        } 
        </style> 
    </head> 
    <body> 
        <a href="http://java2s.com"> Visit the java2s.com </a> 
    </body> 
</html>
  
Click to view the demo

[href] matches any element with an href attribute. [href] doesn't look at the value.

The following table lists the conditions for the element attribute selector

ConditionDescription
[attr]Selects elements who has attribute attr.
[attr="val"]Selects elements who has attr with value val.
[attr^="val"]Selects elements who has attr. The attr's value starts with the val.(CSS3)
[attr$="val"]Selects elements who has attr. The attr's value ends with the val. (CSS3)
[attr*="val"]Selects elements who has attr. The attr's value contains the val. (CSS3)
[attr~="val"]Selects elements who has attr. The attr's value contains multiple values, one of them is val.
[attr|="val"]Selects elements who has attr. The attr's value is a hyphenseparated list of values, the first of which is val.

The ~= condition deals with attributes that support multiple values. And the values are separated by a space character. [class~="value"] is equivalent to .value.

 
<!DOCTYPE HTML> 
<html> 
    <head> 
        <title>Example</title> 
        <style type="text/css"> 
        [class~="class1"] { 
            border: thin black solid; 
            padding: 4px; 
        } 
        </style> 
    </head> 
    <body> 
        <a class="class1 class2" href="http://java2s.com"> 
            Visit the java2s.com 
        </a> 
        <span class="class1">HTML</span>
    </body> 
</html>
  
Click to view the demo

The |= condition is useful for hyphens-separated value.

 
<!DOCTYPE HTML> 
<html> 
    <head> 
        <title>Example</title> 
        <style type="text/css"> 
        [lang|="en"] { 
        border: thin black solid; 
        padding: 4px; 
        } 
        </style> 
    </head> 
    <body> 
        <a lang="en-us" href="http://java2s.com"> Visit the java2s.com </a> 
        <span lang="en-gb">HTML</span>
    </body> 
</html>
  
Click to view the demo
Home 
  HTML CSS Book 
    CSS  

Selectors:
  1. Selecting All Elements
  2. Selecting Elements by Type
  3. Selecting Elements by Class
  4. Selecting Elements by ID
  5. Selecting Elements by Attribute
Related: