I need t...">

Get first and last class using jQuery

Maybe a question for beginners. I have a line of code like this:

<div class="template active"> 

I need to get each class for myself.

I tried this code:

 $(this).attr("class"); 

From this code, I get the "template active". I need one line with a "template" and another with an "active".

What is the best jQuery feature for this? Example?

+8
javascript jquery
source share
8 answers
 var classes = $(this).attr("class").split(/\s/); classes[0] === 'template' classes[1] === 'active' 

If there are more than two class names, and you want to get only the first and last (this was your question), you can call:

 classes[0] = first class classes[classes.length -1] = last class 
+14
source share
 var class= $(this).attr("class").split(" ").pop(); 
+7
source share

You can use the Javascript split () method:

 var classes = $(this).attr("class").split(" "); 
+5
source share

If you are checking to see if there is an HTML element in the class, you can use .hasClass ('classname'), which will return true or false.

Otherwise, if you are trying to view a list, I think you will split the string into an array. The other two answers that have just been posted will show you how to do this. :)

+1
source share
 var class= $(this).attr("class").split(" ") (for i in class) { alert(class[i])} 
0
source share

I think this is an easy way.

 $(".element").last().addClass("highlight"); 
0
source share

You can also use this method 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]+"'"); 

Contact LIVE DEMO

0
source share

you can use: last

 $(".element:last") 
0
source share

All Articles