8

I have several classes that I want to select .group1-1 .group1-2 .group1-3, each one of these has 50 elements under it.

Is there a way to select all classes that start with group1 (so I end up selecting group1-1, group1-2, group1-3), something like $(".group1"+*)

twitter
  • 8,425
  • 6
  • 21
  • 19

2 Answers2

12

You can also use something along the lines of this if you'd like to avoid regex:

$("[class^='group1-']").click(function () {
    var groupNumber = $(this).attr('class').split('-')[1];
    alert('Yep, you clicked group1-' + groupNumber); 
});

Example here: http://jsfiddle.net/iwasrobbed/7bjtb/

iwasrobbed
  • 45,890
  • 20
  • 149
  • 193
  • 7
    Take care as this solution will not match for elements that have multiple classes, if the 'group1-*' class is not the first listed in the 'class' attribute. See http://jsfiddle.net/vQk9U/2/ for an example of this. – Greg Sadetsky Jan 31 '14 at 21:43
  • ... in addition, switching from '^=' to '\*=' will work, until you run into issues where 'group1-' matches as a substring of another class name, such as 'mygroup1-*' :-) – Greg Sadetsky Jan 31 '14 at 21:51
2

This question discusses jquery wildcard / regex selectors. Which basically allow you to use a regular expression to specify matching classes.

Community
  • 1
  • 1
John Weldon
  • 38,339
  • 11
  • 92
  • 126