jQuery Get Class That Starts With A String
Asked Answered
I

2

5

The selector class can be:

c-1
c-2
c-3
(etc...)

The selector can also have other classes, so here is an example of a possible HTML:

<div class="foo c-2 foofoo"></div>

I want to get the number after the c. In this case - I'll get 2.

How can I do that?

Incumber answered 15/9, 2013 at 9:25 Comment(1)
Can you accept the answer that worked for you @Ariel?Deel
M
11

Try

var el = $('.c-2')//get the element whose class value has to be extracted
var val = el.attr('class').match(/\bc-(\d+)\b/)[1]
Malony answered 15/9, 2013 at 9:29 Comment(1)
this is really amazing!Asoka
N
1

If you sure that no other integers present in your class

try

var s ="foo c-2 foofoo";
var result = /\d+(?:\.\d+)?/.exec(s);
alert(result);  //2 is the result

Fiddle

Nynorsk answered 15/9, 2013 at 9:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.