Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 232
Jens Törnell Avatar asked Feb 02 '11 09:02

Jens Törnell


1 Answers

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
like image 153
jAndy Avatar answered Nov 08 '22 20:11

jAndy