Might be a newbie question. I have a code line like this:
I need to get each class for itself.
var classes = $(this).attr("class").split(/\s/);
classes[0] === 'template'
classes[1] === 'active'
If there are more than two classnames and you only want to get the first & last (that was your question) you can call:
classes[0] = first class
classes[classes.length -1] = last class
var class= $(this).attr("class").split(" ").pop();
var class= $(this).attr("class").split(" ")
(for i in class)
{ alert(class[i])}
If you're checking to see if a HTML element has a class, you can use .hasClass('classname') which would return true or false.
Otherwise, if you're trying to see a list, I think you'll have split the string into an array. The other two answers that were just posted will show you how. :)
I think that this is the easy way.
$(".element").last().addClass("highlight");
You can do this way too using map
:-
var ArrayData = $.map($(this).attr("class").split(' '), function(value){
return value;
});
alert("first class = '"+ArrayData[0]+"'");
alert("last class = '"+ArrayData[ArrayData.length - 1]+"'");
Refer LIVE DEMO