Paul Paul - 20 days ago 8
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:

alert(classString);


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];
alert(myClass);


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.

Answer

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"
alert(myClass);

Fiddle: https://jsfiddle.net/d927r9z4/


If you run

var classArray = classString.split(' ');
console.log(classArray);

You'll get an array of the classes:

["blog","button","main"]

Fiddle: https://jsfiddle.net/d927r9z4/1/

Comments