JQuery href Link Optimization

I am changing the tag class "a" according to the file type "href". It is working fine. Here is 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 to optimize this code?

+4
source share
3 answers

If optimization, you want to make the code more concise and convenient, then you can create a lookup 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]]); } }); 
+6
source

try it

 $(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

+1
source

Try the case of switching to $ ('# divComment a'). attr ('href').

0
source

All Articles