76

For whatever reason I have these classes called .main_sub1, .main_sub2 etc. Never mind why I can't have .main .sub.

Is there a way with jQuery, sort of in the way it is possible to do with attributes, to get the classes containing main?

Keavon
  • 6,837
  • 9
  • 51
  • 79
David Andersson
  • 1,246
  • 2
  • 11
  • 17

3 Answers3

182

Using $("[class^=main]") will select all elements whose classname starts with 'main'. Take a look at jQuery docs about selectors, there are a lot of other variations you can use, for example:

  • [class*=main] will select elements whose classname contains 'main'
  • [class~=main] will select elements whose classname has the word 'main' (delimited with spaces)
  • [class$=main] will select elements whose classname ends in 'main'
Paul
  • 19,704
  • 14
  • 78
  • 96
Tatu Ulmanen
  • 123,288
  • 34
  • 187
  • 185
  • will this work when class has been added to the element by 'addClass' method and not as an attribute? – ZX12R Sep 14 '16 at 10:48
17

Yes, you can use an attribute selector to match certain values for the class attribute.

$('[class^=main]') // class begins with "main"
$('[class*=main]') // class contains "main" anywhere within it
Jimmy
  • 35,686
  • 13
  • 80
  • 98
3

In this instance, I would just treat the class attribute in the same way as you do a standard attribute.

$("[class*=main]")
James Wiseman
  • 29,946
  • 17
  • 95
  • 158