Automatically Discover Document Links And Apply Class

$('a[href]').each(function() {
   if((C = $(this).attr('href').match(https://cdn.css-tricks.com/[.](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")

Comments

  1. User Avatar
    Mike
    Permalink to comment#

    Works like a champ!

  2. User Avatar
    Nertus
    Permalink to comment#

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

  3. User Avatar
    Tem Corner
    Permalink to comment#

    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; }

    • User Avatar
      Ahmed
      Permalink to comment#

      yes, that’s right css way is better than jquery way(personal opinion) :).

  4. User Avatar
    gautam
    Permalink to comment#

    it Awesome thanks

Submit a Comment

Posting Code

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.

icon-anchoricon-closeicon-emailicon-linkicon-logo-staricon-menuicon-nav-guideicon-searchicon-staricon-tag