Reputation: 24808
Might be a newbie question. I have a code line like this:
<div class="template active">
I need to get each class for itself.
I tried this code:
$(this).attr("class");
From that code I get "template active". What I need is one string with "template" and another with "active".
What is the best jQuery function for that? Example?
Upvotes: 8
Views: 8573
Reputation: 18064
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
Upvotes: 0
Reputation: 348
I think that this is the easy way.
$(".element").last().addClass("highlight");
Upvotes: 0
Reputation: 11028
var class= $(this).attr("class").split(" ")
(for i in class)
{ alert(class[i])}
Upvotes: 0
Reputation: 3841
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. :)
Upvotes: 1
Reputation: 236202
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
Upvotes: 14
Reputation: 263187
You can use the Javascript split() method:
var classes = $(this).attr("class").split(" ");
Upvotes: 5