Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current element's classes in jQuery

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

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

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

For instance, in this case, I want the variable classes to have a value of .example.whatever instead of example whatever.

I've searched and the only solution that seemed to be provided is the code I demonstrated above.

like image 370
UserIsCorrupt Avatar asked Jun 23 '26 08:06

UserIsCorrupt


1 Answers

I'm really very uneasy about this, since replacing spaces with periods will give the representation of stacked classes, when the classes aren't 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

like image 104
Sampson Avatar answered Jun 25 '26 00:06

Sampson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!