简体   繁体   中英

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? eg

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

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

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.

Not simply using CSS, but you can create a custom selector .

    jQuery.expr[':'].hrefEndsWith = function(
        objNode,
        intStackIndex,
        arrProperties,
        arrNodeStack
        ){
        // The list of arguments gets passed as a string -
        var arrArguments = arrProperties.split(',');
        // Create a jQuery version of this node.
        var jThis = $( objNode );
        // Check to see if this node ends with (we only need to find
        // one of the titles to qualify).
        for (var i = 0 ; i < arrArguments.length ; i++){
            // Check for title equality.
            if (jThis.attr( "href" ).endsWith(arrArguments[i])){
                // We found a href match, return true to
                // indicate that this node should be included
                // in the returned jQuery stack.
                return true ;
            }
        }
        // If we have made it this far, then we found no
        // match. Return false to indicate that this node
        // did not match our selector.
        return false ;
    }

    // Use it
    jQuery("a:hrefEndsWith('.pdf', '.txt', '.xls')");

Or if you don't need all that you could just write a JS function to create your selector.

function getEndsWithSelector(names) {
    return names.map(n => 'a[href$=".'+name+'"]').join();
}

jQuery(getEndsWithSelector('pdf', 'txt', 'xls'))

You would have to add some escaping if you need to support special characters

I had some issues using ".attr()". The browser would return "TypeError: $(…).attr(…)", so after some research I found that if I replaced ".attr()" with ".prop()" it fixed the issue.

Here's some explanations regarding both: .prop() vs .attr()

Thanks for the function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM