0
<div class="cd1"></div>
<div class="cd2"></div>
<div class="cd3"></div>
<div class="cd4"></div>
<div class="cd5"></div>

How can I select base on 'cd' char?

I tried $('.cd*) but doesn't work.
ivy ong
  • 101
  • 1
  • 6

4 Answers4

2

To access the classes containing a specific text at the beggining:

$("[class^=cd]")

and To access the classes containing a specific text at the end:

$("[class$=cd]")
M Reza Saberi
  • 7,134
  • 9
  • 47
  • 76
  • thanks, but can this be used together with $(this)? I want to check targeted hasClass($("[class^=cd]")).. possible? – ivy ong Dec 31 '14 at 09:18
  • If you have a specific element to check this on, you could use the `contains()` on the targeted element! as I have shown in http://jsfiddle.net/MR_Saberi/puhuh2ue/2/ – M Reza Saberi Dec 31 '14 at 09:35
2

Try selecting the attribute class:

$('[class^=cd]')
kapantzak
  • 11,610
  • 4
  • 39
  • 61
1

While you could use $("[class^=cd]"), it would be very fragile and it's not a good idea: As soon as you add other classes, you could break it. These would fail to match it, for instance:

<div class="foo cd1"></div>
<div class="bar cd2"></div>

Instead, add a second class to all of these elements that doesn't vary:

<div class="cd cd1"></div>
<div class="cd cd2"></div>
<div class="cd cd3"></div>
<div class="cd cd4"></div>
<div class="cd cd5"></div>

Then use $(".cd").

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

wrap it with div, add some class to it

example:

 <div class="cd">
    <div class="cd1"></div>
    <div class="cd2"></div>
    <div class="cd3"></div>
    <div class="cd4"></div>
    <div class="cd5"></div>
 </div>

then you can use this selector $('.cd > div)

Branimir Đurek
  • 632
  • 5
  • 13