Element or class LIKE selector for jQuery?

Solution 1:

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'

Solution 2:

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

Solution 3:

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

$("[class*=main]")