Part 4.6Attribute selector

The attribute selector is used to select elements that have a specific attribute value, that is, elements that have a specified attribute and have a specified value.

Attribute selector

The attribute selector is a powerful selector. This website uses it on links to determine external links from internal links.

Example attributes include:

  • href
  • placeholder
  • email
  • number

Square brackets are used to start an attribute selector:

CSS
input[type=number]{
	background: #f00;
}
        

The above sample will make the background of any input element which has the attribute type="number".

As well as being able to specify a value like number, regular expressions such as ^=http can be used (this regular expression will check if a string starts with http).

Select all where attribute exists

It's also possible to select all elements which have an attribute regardless of it's value. This is a very useful tool because it allows you to select all elements without a class, for instance, using CSS.

This example demonstrates how to select all elements with a class attribute, regardless of what class this is:

CSS
input[class]{
	background: #f00;
}
        

This next version will do the opposite, selecting all elements without a class (it uses the CSS :not pseudo-selector):

CSS
input:not([class]){
	background: #00f;
}
        
Feedback 👍
Comments are sent via email to me.