CSS attribute selector can be used to select DOM elements based on matching substring of attribute values. We can use attribute substring selectors in multiple ways.
[att^=val] | attribute value begins with val. If val is empty, then it does not do anything. |
[att$=val] | attribute value ends with val. If val is empty, then it does not do anything. |
[att*=val] | attribute contains val. If val is empty, then it does not do anything. |
Note that in substring matching there is no requirement of match having space or any other boundary character before or after.
Example – attribute value prefix match selector
a tag with href beginning with “#” will have different color
<style type="text/css"> a[href^="#"] { color:red; } </style> <a href="#link1">link to #link1</a><br/> <a href="#link2">link to #link2</a><br/> <a href="/">link to /</a><br/>
Example – attribute value suffix match selector
a tag with href ending at “.html” will have different color
<style type="text/css"> a[href$=".html"] { color:red; } </style> <a href="/demo2/hello.html">link to hello.html</a><br/> <a href="/">link to /</a><br/>
Example – attribute value contains match selector
a tag with title containing “hello” will have different color
<style type="text/css"> a[title*="hello"] { color:red; } </style> <a href="/" title="ahello world">link having hello in title</a><br/> <a href="/">link to /</a><br/>
Related
- CSS type selectors - define style by element name
- CSS universal selector
- CSS attribute presence and value selectors
- CSS class selectors - define style by class name
- CSS - style for element having two classes (both)
- CSS id selectors - define style by element id