-1

For example:

<div class="home current">home</div>

When I use $(this).attr("class"), it simply returns "home current". I want to get the "home" attribute only. How can I achieve this?

Liang
  • 1,127
  • 2
  • 11
  • 22
  • 3
    Your question isn't clear. Are you trying to determine if the div has the 'home' class, or are you trying to get the first class listed in the list of classes? – kinakuta Mar 20 '13 at 15:29
  • Possible duplicate: [jQuery - get the first class only from a element](http://stackoverflow.com/q/3203966/1456376) – insertusernamehere Mar 20 '13 at 15:31

5 Answers5

2

If you know the class name and want to check if an element has it, you can use .hasClass()

// will return true if the element has that class applied to it
$(elem).hasClass('home'); 

On the other hand, if you want each class applied to an element separately, you can split by space and iterate:

var classes = $(elem).attr('class').split(' ');
for(var i=0; i<classes.length; i++) {
   classes[i]; // each class name
}
techfoobar
  • 65,616
  • 14
  • 114
  • 135
1

The class attribute returns the space delimitered list of css classes assigned to the element, to convert this into an array use the split method on the string, and to retrieve the first one, use the [0] indexer, as in:

 var firstClass = $(this).attr('class').split(' ')[0]
tonycoupland
  • 4,127
  • 1
  • 28
  • 27
0
var allClass= $(this).attr("class");
var class = allClass.replace("current", "");

this will work if you only have "current" as an additional class

Lucky Soni
  • 6,811
  • 3
  • 38
  • 57
0

Is there a specific reason that you need to pull the class list. If you know the class you are looking for and just need to check if the object has the class home, you could do this:

$(this).hasClass("home");

Otherwise, you could just split the result and check for whatever class you need.

var classAttr = $(this).attr("class");
var classes = classAttr.split(" "); 
uadrive
  • 1,249
  • 14
  • 23
0

It seems you need the primary class of the element.

var primaryClass= $(this).attr('class').split(' ')[0].

Remember this line may cause exception if no class applied,while the time you using it.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307