Att&;ribute selectors
are a particularly helpful subset of CSS selectors. They allow us to
specify an element by one of its HTML properties, such as a link's title attribute or an image's alt attribute. For example, to select all images that have an alt attribute, we write the following:
In versions prior to 1.2, jQuery used XML Path Language (XPath)
syntax for its attribute selectors and included a handful of other
XPath selectors. While these basic XPath selectors have since been
removed from the core jQuery library, they are still available as a
plugin: http://plugins.jquery.com/project/xpath/
Styling links
Attribute selectors accept a wildcard syntax inspired by regular expressions for identifying the value at the beginning (^) or ending ($) of a string. They can also take an asterisk (*) to indicate the value at an arbitrary position within a string or an exclamation mark to indicate a negated value.
Le&;&;t's say we
want to have different styles for different types of links. We first
define the styles in our stylesheet:
a {
attribute selectorsstyles, definingcolor: #00c;
}
a.mailto {
background: url(images/mail.png) no-repeat right top;
padding-right: 18px;
}
a.pdflink {
background: url(images/pdf.png) no-repeat right top;
padding-right: 18px;
}
a.henrylink {
background-color: #fff;
padding: 2px;
border: 1px solid #000;
}
Then, we add the three classes — mailto, pdflink, and henrylink — to the appropriate links using jQuery.
To add a class for all email links, we construct a selector that looks for all anchor elements (a) with an href attribute ([href) that begins with mailto: (^=mailto:]), as follows:
$(&;document).ready(function() {
$('a[href^=mailto:]').addClass('mailto');
});
To add a class for all links
to PDF files, we use the dollar sign rather than the caret symbol. This
is because we're selecting links with an href attribute that ends with .pdf:
$(document).ready(function() {
$('a[href^=mailto:]').addClass('mailto');
$('a[href$=.pdf]').addClass('pdflink');
});
Attribute selectors can be combined as well. We can, for example, add a henrylink class for all links with an href value that both starts with http and contains
henry anywhere:
$(document).ready(function() {
$('a[href^=mailto:]').addClass('mailto');
$('a[href$=.pdf]').addClass('pdflink');
$('a[href^=http][href*=henry]')
.addClass('henrylink');
});
With the three classes applied to the three types of links, we should see the following:
Note the PDF icon to the right of the Hamlet link, the envelope icon next to the email link, and the white background and black border around the Henry V link.