Paul Paul - 4 months ago 22
CSS Question

How can I get only the first class of an element?

I am trying to get the class of an element upon hovering on it.

So far I have managed to get a bit of progress:

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

This gives me all the classes of the element (unfortunately more than one). For instance, if I do:


I get the string "blog button main". I want to get just the first word of that string (the first class). I've tried:

var myClass = $(classString).text().split(' ')[0];

expecting to get just "blog", but I get an empty string. I'm sure this is just a basic mistake I am making, but I can't see it.


classString is already a string and split is a prototype function of a string, not a jQuery function.

var classString = $(this).attr('class'); // "blog button main"
var myClass = classString.split(' ')[0]; // "blog"


If you run

var classArray = classString.split(' ');

You'll get an array of the classes: