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?

2
  • 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 8, 2010 at 13:24
  • 1
    In general I would not trust all browsers to give them back to you in the same order. Jul 8, 2010 at 13:37

3 Answers 3

138

You need to split that into an array:

console.log(jQuery('selector').attr('class').split(' ')[0]);
2
  • 4
    Or use a regex: var first = $('#foo').attr('class').replace(/^(\S*).*/, '$1');
    – Pointy
    Jul 8, 2010 at 13:28
  • In this case, you should use prop instead of attr.
    – Druska
    Apr 19, 2013 at 15:23
9
var first = jQuery.attr('class').split(" ")[0];
1
  • 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 8, 2010 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]

Not the answer you're looking for? Browse other questions tagged or ask your own question.