Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery add class to href if link contains specific text

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:

  • Document1.pdf
  • Song1.mp3
  • Song2.m4a
  • Document2.doc

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.

like image 224
Sam Skirrow Avatar asked Apr 08 '13 12:04

Sam Skirrow


2 Answers

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.

like image 121
James Hill Avatar answered Oct 20 '22 01:10

James Hill


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.

like image 31
Ejaz Avatar answered Oct 19 '22 23:10

Ejaz