7

I have a few links that look like this:

<a href="#" class="somelink rotate-90"> ... </a>

How can I bind a function to all elements that have a class that starts with "rotate-" ?

Alex
  • 66,732
  • 177
  • 439
  • 641

1 Answers1

10

You can use starts with selector like this:

$('a[class^="rotate-"]')

Description: Selects elements that have the specified attribute with a value beginning exactly with a given string.

So your code should be:

$('a[class^="rotate-"]').click(function(){
  // do stuff
});

Note: If you want to find out elements that contain certain text anywhere in their attributes, you should do this instead:

$('a[class*="rotate-"]').click(function(){
  // do stuff
});
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
  • *all elements* not just `a` (though that does give a specific example, obviously). – David Thomas Nov 12 '10 at 13:44
  • 1
    @David Thomas: That is quoted from jQuery docs. Focus on the example I have provided :) – Sarfraz Nov 12 '10 at 13:45
  • The starts-with `^` selector will break with precisely the kind of sample the OP posted. – Roatin Marth Nov 12 '10 at 13:47
  • tx. it works with *, but not with ^. I think it's because I have multiple classes on the link, and the one I'm targeting is not the first – Alex Nov 12 '10 at 13:48
  • @Roatin Marth: I saw that and for that reason I have posted the solution for that too which can be seen at the bottom :) – Sarfraz Nov 12 '10 at 13:48
  • The contains `*` selector will have false positives with anything like `foorotate-`, `barrotate-`. This may be ok for the OP however? – Roatin Marth Nov 12 '10 at 13:50
  • yes, in my case there shouldn't be any classes with similar names :) the link is actually a thumbnail image I'm trying to rotate on mouse over – Alex Nov 12 '10 at 13:51
  • @Alex: That is because the text `rotate-` does not come at the start as you have shown in the example of your question. If `rotate-` is to be found anywhere in the attribute, you should use `*` instead. Use `^` when text appears at the start of the attribute. – Sarfraz Nov 12 '10 at 13:51
  • Well, `a[class*="rotate-"]` will also match `class="anotherrotate-90"`. *If* that's a problem I believe this will be the solution: `a[class^=" rotate-"], a[class*=" rotate-"]`, i.e. unioning the sets containing the class `rotate-*` first or anywhere else. – jensgram Nov 12 '10 at 13:53
  • @jensgram: Totally agreed, let's see what OP is up to :) – Sarfraz Nov 12 '10 at 13:55
  • @jensgram: good idea. However that also fails to find links that have `"rotate-xxx"` as the first class. I think you meant `a[class^="rotate-"]` in the first selector (note no space). – Roatin Marth Nov 12 '10 at 14:14
  • @Roatin Marth Yes, that was a typo :) Thanks – jensgram Nov 12 '10 at 14:17