Style Document Links on a Page using CSS and jQuery

The behavior and style of links can be easily specified using CSS, and with a little bit of jQuery, you can avoid applying CSS directly in the HTML. I will show you an example. Let us assume we have a couple of hyperlinks on the page, some of them linking to websites and the others linking to .doc/.xls documents on the web. Now if you have to highlight the hyperlinks linking to only .doc files, here’s how to do so using CSS and jQuery

<html>
<
head>
<
title>Style Document Links on a Page</title>
<
style type="text/css">
.docs
{
color:Gray;
font-style:italic;
background: url(someimage.png) no-repeat center right;
}
</style>
<
script language="javascript" type="text/javascript"
src="http://code.jquery.com/jquery-latest.js"></script>
<
script language="javascript" type="text/javascript">
$(function() {
$('a[href$=.doc]').addClass('docs');
});
</script>
</
head>
<
body>
<
form>
<
div>
<
a href="http://www.dotnetcurry.com">DotNetCurry</a>
<
a href="http://www.microsoft.com/smserver/docs/collectsecurity.doc">
Security Paper</a>
<
a href="http://www.microsoft.com/exchange/evaluation/03SecEnh.doc">
Exchange Server 2003</a>
<
a href="http://www.microsoft.com/msft/download/financialhistoryFY.xls">
Microsoft Fiscal History</a>
</
div>
</
form>
</
body>
</
html>

Observe this piece of code

$('a[href$=.doc]').addClass('docs');

We are using an attribute selector to highlight links containing an href attribute that ends with the extension .doc. The addClass adds the specified class (docs) to each of the set of matched elements

Here’s what the output looks like

image



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: