I have some dynamically populated links in a list on my site that link to files. Is it possible to use jQuery to see if the name of the file ends with .pdf and add a class to the href or similar if the link text ends with .mp3?
For example I have the following links in my list:
I would like to detect the end letters and add different classes to the links, so to the link which has the text Document1.pdf I'd add the class pdf
to the anchor element, and the link with the text Song1.mp3 I'd add the class mp3
to the anchor element.
Use the attribute selector:
$('a[href$=".mp3"]')...
Options:
Attribute Contains Prefix Selector [name|="value"] Selects elements that have the specified attribute with a value either equal to a given string or starting with that string followed by a hyphen (-). Attribute Contains Selector [name*="value"] Selects elements that have the specified attribute with a value containing the a given substring. Attribute Contains Word Selector [name~="value"] Selects elements that have the specified attribute with a value containing a given word, delimited by spaces. Attribute Ends With Selector [name$="value"] Selects elements that have the specified attribute with a value ending exactly with a given string. The comparison is case sensitive. Attribute Equals Selector [name="value"] Selects elements that have the specified attribute with a value exactly equal to a certain value. Attribute Not Equal Selector [name!="value"] Select elements that either don’t have the specified attribute, or do have the specified attribute but not with a certain value. Attribute Starts With Selector [name^="value"] Selects elements that have the specified attribute with a value beginning exactly with a given string. Has Attribute Selector [name] Selects elements that have the specified attribute, with any value. Multiple Attribute Selector [name="value"][name2="value2"] Matches elements that match all of the specified attribute filters.
Check out the API for additional information.
given your all such links have class .file
var exts = ['pdf','xls'];
$('a.file').each(function(){
if($(this).attr('href').match(new RegExp('('+exts.join('|')+')'), 'gi'))
$(this).addClass($(this).attr('href').match(/\w{3}$/gi)[0]);
})
This code will add the extension class to all such links that have file extension in exts
array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With