Choosing the first of several classes

Not sure if you can do this, but I want to select the first of two element classes with jQuery and return it only for the first class.

<div class="module blue">

I want to return 'module'.

tried this:

var state = $('body').attr('class').first();

but none of this works, thanks for any advice.

+5
source share
3 answers

Try

var class = $('.module').attr('class');
var st = class.split(' ');
var firstClass = st[0];
+5
source

Once you have a link to an element, just get its className attribute and separate it with a space, and then you will get the first class at [0] in the split array:

var className = $(element).attr('class'),
    split = className.split(/\s+/g);

alert(split[0] || 'Empty className');
+4
source

How about one liner?

var state = $('body').attr('class').replace(/\s.+$/, "");
+1
source

All Articles