Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - match element that has a class that starts with a certain string

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-" ?

like image 832
Alex Avatar asked Nov 12 '10 13:11

Alex


People also ask

How do you check if an element has a specific class in jQuery?

jQuery hasClass() Method The hasClass() method checks if any of the selected elements have a specified class name. If ANY of the selected elements has the specified class name, this method will return "true".

How do I select a specific class in jQuery?

In jQuery, the class and ID selectors are the same as in CSS. If you want to select elements with a certain class, use a dot ( . ) and the class name. If you want to select elements with a certain ID, use the hash symbol ( # ) and the ID name.

Which selects elements that have the specified attribute with a value beginning exactly with a given string?

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


1 Answers

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
});
like image 86
Sarfraz Avatar answered Oct 11 '22 13:10

Sarfraz