Selector API - Attribute Selector (AND operation)

About

A selector that filtered on an attribute.

Syntax

Element Has Attribute

  • An element:
    • with the tag name E
    • that has a foo attribute
E[foo]
  • All elements with a foo attribute
*[foo]

Attribute Value Exactly Equal

  • An E element whose foo attribute value is exactly equal to bar
E[foo="bar"]
  • All element whose foo attribute value is exactly equal to bar
*[foo="bar"]

Attribute name patterns

  • Contains operator ~=
E[foo~="bar"]
  • Start with operator ^=
E[foo^="bar"]
  • Others
E[foo*="bar"]
E[foo$="bar"]
E[foo|="bar"]

Two or more attribute

E[foo=foo][bar=bar]

Example

And (intersection)

Attribute (Id and class)

#IdName.className  { color:blue; }
/* shorthand for */
*[id=IdName][class=className] { color:blue; }
  • The HTML
<div id="IdName" class="className">The CSS style will be applied on this text</div>
<div>Not on this one</div>
  • The result:

Element and class

div.className  { color:blue; }
/* equivalent to */
div[class~=className]  { color:blue; }
  • The HTML
<div class="className">The CSS style will be applied on this text because it's a div element with the class className</div>
<div>Not on this one because it has no class</div>
  • The result:

Starts with an attribute value

The start with operator ^= permits to define a starts with comparison

Notation example: A class that starts with the string foo

[class^="foo"]

Full example

  • All element with a class that starts with the string foo will get a red color
*[class^="foo"] {
  color: red
}
  • The HTML
<p>A paragraph without class</p>
<p class="foo-suffix other-class">A paragraph with a class that starts with foo</p>
  • Output: The paragraph with the class foo-suffix is red

Button

  • The HTML
<button role="button" aria-label="Delete item 1">Delete</button>
  • The CSS
*[role="button"] {
  /* the attribute selector */
	background-color:#44c767;
	border-radius:28px;
	display:inline-block;
	color:#ffffff;
        padding:16px 31px;
}
*[role="button"]:hover {
	background-color:#5cbf2a;
}
*[role="button"]:active {
	position:relative;
	top:1px;
}
  • The result:

Powered by ComboStrap