Reputation: 425
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="module 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.
Upvotes: 5
Views: 5324
Reputation: 77
You just need to select the first attribute.
You can try
<div class="category">A</div>
<div class="category">B</div>
I have two input field with same class name I can select the first one by following code
//I have added trigger function which might not be needed
$(".category").first().trigger('click')
Upvotes: 0
Reputation: 165
How about a one liner?
var state = $('body').attr('class').replace(/\s.+$/, "");
Upvotes: 2
Reputation: 111900
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');
Upvotes: 4
Reputation: 2784
Try
var class = $('.module').attr('class');
var st = class.split(' ');
var firstClass = st[0];
Upvotes: 7