0

I need to get the name of the second class from an element like this:

<div class="item getthisclass"></div>

Using this will pick both classes:

var selectedClass = $(this).attr('class');

or this does not select anything.

$(this).not('.item').attr('class');

How can I do this?

santa
  • 12,234
  • 49
  • 155
  • 255

2 Answers2

3

You can use .split().

// Create an array of class names...
var classes = $(this).attr('class').split(/\s+/);

// Now you can grab the by index...
var firstClass = classes[0]
var secondClass = classes[1];
var thirdClass = classes[2];
Bill Criswell
  • 32,161
  • 7
  • 75
  • 66
0

I often use the classList object(it can also be used to add, remove or toggle classes). I find it more useful than the jQuery attr('class') way. Try:

this.classList

Reference

tewathia
  • 6,890
  • 3
  • 22
  • 27