jQuery add class to href if link contains specific text
append, href, javascript, jquery
Solution
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.
Problem
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.