Show classes​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​...">

Get current element classes in jQuery

​<button id="test" class="example whatever">Show classes</button>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

$('button').click(function(){
  var classes = $(this).attr('class');
  alert(classes);
});​

The code above returns the contents of the attribute class. How can I get it to return formatted classes?

For example, in this case, I want the variable to classeshave a value .example.whateverinstead example whatever.

I searched, and the only solution that seemed to be presented was the code I demonstrated above.

+3
source share
2 answers

I am very embarrassed about this, since replacing spaces with periods will give an idea of ​​the classes stacked when the classes are not really stacked, but here you go:

// class="foo bar fiz buz" -> .foo.bar.fiz.buz
this.className.replace( /^|\s/g , "." );

Demo: http://jsbin.com/awitef/edit#javascript,html

+6
source
$('button').click(function(){
  var classes = $(this).attr('class');
  alert("." + classes.split(" ").join(".") );
});

Spell here: http://jsfiddle.net/wxDEh/3/

+1
source

All Articles