Search code examples
javascriptjqueryanchorhrefselector

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.

jQuery('a[href$=".pdf|.doc|.docx"])

And secondly, is there a way to target different cases for the file extensions e.g. Pdf, PDF and pdf?


Solution

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

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

    $("a").filter(function(){
      return $(this).attr("href").match(/\.(pdf|doc|docx|ppt|pptx|xls|slxs|epub|odp|ods|txt|rtf)$/i);
    }).css("color", "red")
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></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.