2

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/

l2aelba
  • 21,591
  • 22
  • 102
  • 138

2 Answers2

8

You can use a regex :

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

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

Samuel Caillerie
  • 8,259
  • 1
  • 27
  • 33
2

You can use match function:

var id = $(".main").attr("class").match(/\d+/g).join('');
Ram
  • 143,282
  • 16
  • 168
  • 197