A Web Design Community curated by Chris Coyier

A little dab'll do ya

Code Snippets

Home » Code Snippets » jQuery » Automatically Discover Document Links And Apply Class Submit one!

Automatically Discover Document Links And Apply Class

$('a[href]').each(function() {
   if((C = $(this).attr('href').match(/[.](doc|xls|pdf)$/))) {
       $(this).addClass(C[1]);
   }
});

This will look through every a element on the page. If the href attribute of it has a .doc, .xls, or .pdf in it, it will apply the appropriate class name to it (e.g. class="doc")

Subscribe to The Thread

  1. Mike says:

    Works like a champ!

  2. Nertus says:

    $(“a[href$='.doc']“).addClass(‘doc’);

  3. Tem Corner says:

    Although IE6 would degrade to a normal link, this can be done by CSS.


    a[href$='.doc'] { padding-right:16px; background: transparent url(images/doc.png) no-repeat top right; }

It's Your Turn

At this moment, you have an awesome opportunity* to be the person your mother always wanted you to be: kind, helpful, and smart. Do that, and we'll give you a big ol' gold star for the day (literally).

Posting tips:
  • You can use basic HTML
  • When posting code, please turn all
    < characters into &lt;
  • If the code is multi-line, use
    <pre><code></code></pre>
Thank you,
--- The Management ---