user2726041 user2726041 - 11 months ago 57
Javascript Question

How to select "a" tag has specific file type in href using jQuery?

I am targeting links which contain various file types in jQuery using:

jQuery('a[href$=".pdf"], a[href$=".doc"], a[href$=".docx"], a[href$=".ppt"], a[href$=".pptx"], a[href$=".xls"], a[href$=".slxs"], a[href$=".epub"], a[href$=".odp"], a[href$=".ods"], a[href$=".txt"], a[href$=".rtf"]').before('<span class="glyphicon glyphicon-file"></span> ');

Firstly, is there a way of reducing the repetition? e.g.


And secondly, is there a way to target different cases for the file extensions e.g.

Answer Source

You can filter selected element using .filter(). In filter function check extension using regex in String.prototype.match().

   return $(this).attr("href").match(/\.(pdf|doc|docx|ppt|pptx|xls|slxs|epub|odp|ods|txt|rtf)$/i);
}).before("Some html");

  return $(this).attr("href").match(/\.(pdf|doc|docx|ppt|pptx|xls|slxs|epub|odp|ods|txt|rtf)$/i);
}).css("color", "red")
<script src=""></script>
<a href="file.pdf">pdf</a>
<a href="file.doc">doc</a>
<a href="file.html">html</a>
<a href="file.docx">docx</a>
<a href="file.ppt">ppt</a>
<a href="file.php">php</a>
<a href="file.slxs">slxs</a>
<a href="file.txt">txt</a>

Note that i flag at the end of regex match case insensitive.