Narazana
Narazana

Reputation: 1950

jQuery Optimize link "href" selection

I'm changing the class of "a" tag according to "href" file type. It works fine. Here's the code:

    $('#divComment a[href$=".pdf"]').removeClass().addClass("pdf");
    $('#divComment a[href$=".doc"]').removeClass().addClass("word");
    $('#divComment a[href$=".docx"]').removeClass().addClass("word");
    $('#divComment a[href$=".zip"]').removeClass().addClass("zip");
    $('#divComment a[href$=".jpg"]').removeClass().addClass("image");
    $('#divComment a[href$=".xls"]').removeClass().addClass("excel");
    $('#divComment a[href$=".xlsx"]').removeClass().addClass("excel");

How do I optimize this code?

Upvotes: 4

Views: 207

Answers (3)

Felix Kling
Felix Kling

Reputation: 816422

If by optimization, you mean to make the code more concise and maintainable, then you could create a look-up table.

Example:

var extensions = {
    '.pdf': 'pdf',
    '.doc': 'word'
    // ...
};

$('#divComment a').each(function() {
    var match = this.href.match(/\..+$/);
    if(match && extensions[match[0]]) {
        $(this).removeClass().addClass(extensions[match[0]]);
    }
});

Upvotes: 6

sankar.suda
sankar.suda

Reputation: 1147

try this

$(document).ready(function(){

var extensions = {
'pdf': 'pdf',
'doc': 'word'
};


$('#divComment a').each(function() {
    var href = this.href;
    var ext = href.split('.').pop().toLowerCase();

    if(extensions[ext]) {
        $(this).addClass(extensions[ext]);
    }
});

});

idea from @Felix Kling post..

jsfiddle

Upvotes: 1

MrJD
MrJD

Reputation: 1889

Try a switch case on the $('#divComment a').attr('href').

Upvotes: 0

Related Questions