Problem with 'addClass' in jquery
<html> <head> <style type="text/css"> a.red { color: red; } a.green { color: green; } a.yellow { color: yellow; } </style> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"> </script> <script type="text/javascript"> $(document).ready(function() { $('a[href^=red]').addClass('red'); $('a[href$=.jpg]').addClass('green'); $('a[href*=pic]').addClass('yellow'); }); </script> </head> <body> <a href="red.gif">red</a></br> <a href="green.jpg">green</a></br> <a href="yellowpic.png">yellow</a> </body> </html> Question:
Only red color works in the front-end, green and yellow do not work, why?
From the documents
jQuery( "[attribute='value']" ) attribute : attribute name.
Value : attribute value. It can be either an unquoted single word or a quote string.
You must add " around the matched string.
$('a[href^="red"]').addClass('red'); $('a[href$=".jpg"]').addClass('green'); $('a[href*="pic"]').addClass('yellow'); ^ ^ This way it will work on more than one word, for example
$('a[value*="some value"]') You need to go out . using \\. since it is a reserved character in jquery selectors or just wrap the attribute value in quotation marks.
$(document).ready(function() { $('a[href^=red]').addClass('red'); $('a[href$=\\.jpg]').addClass('green'); // < --Here //$('a[href$="jpg"]').addClass('green'); $('a[href*=pic]').addClass('yellow'); }); The problem is that in the second line you get a syntax error, and your third line does not execute when the script breaks.
From docs
To use any of the metacharacters (such as!) # $% & '() * +,. / :; <=>? @ [] ^ `{|} ~) as the literal part of the name, it must be escaped with two backslashes: \.