69

The element looks like this:

<li class="blah active"> ... </li>

jQuery.attr('class') will return both classes. How can I get only the 1st class ('blah' in this case) with jQuery?

Alex
  • 66,732
  • 177
  • 439
  • 641
  • 5
    the problem is, that if you add/remove classes via jquery, it will not save the correct order of the items. so maybe you want to check, if that class is in the list, instead of getting the first one. – cRichter Jul 08 '10 at 13:24
  • 1
    In general I would not trust all browsers to give them back to you in the same order. – Matt Evanoff Jul 08 '10 at 13:37

3 Answers3

137

You need to split that into an array:

console.log(jQuery('selector').attr('class').split(' ')[0]);
Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
9
var first = jQuery.attr('class').split(" ")[0];
gblazex
  • 49,155
  • 12
  • 98
  • 91
  • and he said "`jQuery.attr('class')` will return both classes", which indicates that by `jQuery` he meant an instance of the jQuery object, not the contructor function which invokes `jQuery.fn.init` – gblazex Jul 08 '10 at 13:36
2

You can use the following to get the first class only from an element:

var firstClass = jQuery('selector')[0].classList[0]
Grant Miller
  • 27,532
  • 16
  • 147
  • 165
jackotonye
  • 3,537
  • 23
  • 31