Web Analytics

Attribute Selectors

Intermediate ~9 min read

What are Attribute Selectors?

Attribute selectors target elements based on their attributes and values. They're powerful for styling forms, links, and data attributes!

Has Attribute [attr]

Select elements that have a specific attribute, regardless of its value.

HTML
CSS
JS

Exact Match [attr=value]

Select elements where the attribute exactly matches the specified value.

HTML
CSS
JS

Starts With [attr^=value]

Select elements where the attribute value starts with the specified string.

HTML
CSS
JS

Ends With [attr$=value]

Select elements where the attribute value ends with the specified string. Great for file types!

HTML
CSS
JS

Contains [attr*=value]

Select elements where the attribute value contains the specified string anywhere.

HTML
CSS
JS

Data Attributes

Style elements based on custom data attributes. Perfect for state management!

HTML
CSS
JS
Pro Tip: Use data attributes with attribute selectors for state-based styling without adding/removing classes with JavaScript!

Summary

  • [attr] - Has attribute
  • [attr=value] - Exact match
  • [attr^=value] - Starts with
  • [attr$=value] - Ends with
  • [attr*=value] - Contains
  • Great for forms, links, and data attributes
  • Case-insensitive with i flag: [attr=value i]

Quick Quiz

Which selector matches attributes that end with a value?

A
[attr^=value]
B
[attr$=value]
C
[attr*=value]
D
[attr~=value]