Element or class LIKE selector for jQuery?

JqueryJquery SelectorsSql Like

Jquery Problem Overview


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?

Jquery Solutions


Solution 1 - Jquery

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 - Jquery

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 - Jquery

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

$("[class*=main]")

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDavid AnderssonView Question on Stackoverflow
Solution 1 - JqueryTatu UlmanenView Answer on Stackoverflow
Solution 2 - JqueryJimmyView Answer on Stackoverflow
Solution 3 - JqueryJames WisemanView Answer on Stackoverflow