CSS attribute substring selectors

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/>
refresh

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/>
refresh

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/>
refresh

Related

Specification

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments