Jens Törnell
Jens Törnell

Reputation: 24808

Get first and last class with jQuery

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

Answers (7)

Siva Charan
Siva Charan

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

Talaveriux
Talaveriux

Reputation: 83

var class= $(this).attr("class").split(" ").pop();

Upvotes: 7

ProgramadorNovato
ProgramadorNovato

Reputation: 348

I think that this is the easy way.

$(".element").last().addClass("highlight");

Upvotes: 0

Vivek
Vivek

Reputation: 11028

var class= $(this).attr("class").split(" ")  
(for i in class)
{ alert(class[i])}

Upvotes: 0

Roy Rico
Roy Rico

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

jAndy
jAndy

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

Fr&#233;d&#233;ric Hamidi
Fr&#233;d&#233;ric Hamidi

Reputation: 263187

You can use the Javascript split() method:

var classes = $(this).attr("class").split(" ");

Upvotes: 5

Related Questions