Question

I want to get the id in class like...

<div class="main demo id_111 test"></div>

<div class="main demo test id_222 test demo"></div>

<div class="id_3 main demo test  test demo"></div>

Result must be 111 , 222 and 3

So I code like this

var id = $(".main").attr("class");
var id = id.split("id_");
var id = id[1].split(" ");
var id = id[0];

$("body").append(id);

But someone know better coding than mine ?

Playground : http://jsfiddle.net/UHyaD/

Was it helpful?

Solution

You can use a regex :

var id = $(".main").attr("class").match(/id_(\d*)/)[1];

JSfiddle : http://jsfiddle.net/scaillerie/UHyaD/1/

OTHER TIPS

You can use match function:

var id = $(".main").attr("class").match(/\d+/g).join('');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top