开发者

selecting the first of multiple classes

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

<div class="mo开发者_Python百科dule blue">

I want to return 'module'.

tried this:

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

but none of that seems to work, thanks for any advice.


Try

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


Once you have a reference to the element, simply get it's className attribute and split it by space, and then you'll have the first class at [0] in the split array:

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

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


How about a one liner?

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜