67

I'm trying to find out how to retrieve the second class name of a class attribute.

For example, having:

<div class="something fooBar"></div>

How can I get the second class named "fooBar" ?

I know you can add, remove, and check a specific class but I couldn't find documentation how to retrieve a second class into a variable.

Community
  • 1
  • 1
CyberJunkie
  • 21,596
  • 59
  • 148
  • 215
  • 1
    @user why do you want to second class name , if you want to change some css propert's on second class still you can say $('.8') – kobe Nov 21 '10 at 19:47
  • @gov, I'm using a second class name because I'm retrieving a lot of data and can't use any more attributes. – CyberJunkie Nov 21 '10 at 19:49
  • @user can you explain it more clear , just i want to learn why do you need all the class names .... // may be i am missing something. – kobe Nov 21 '10 at 19:53
  • 4
    Remember that [neither a `class` nor an `id` may start with a numeric character](http://stackoverflow.com/questions/448981/what-characters-are-valid-in-css-class-names/449000#449000). – David Thomas Nov 21 '10 at 19:59
  • @david but it can end with numeric value, yes? @gov, sure. It's for a voting script. I have vote UP and DOWN, UP and DOWN are the second classes, this way I can tell which button someone clicked on. As for the ID and NAME attributes, I use them for something else. Using a second class trims some excess HTML for me – CyberJunkie Nov 21 '10 at 20:17
  • A class **may** start with a number in HTML (in fact it may contain any HTML-valid non-whitespace character). The trick is that the CSS ‘identifier’ token is more limited, so if you wanted to refer to the class `8` in a stylesheet you would have to use a backslash-escape sequence. – bobince Nov 21 '10 at 20:42
  • @use468312, it certainly can, yep. @bobince, really? That seems contrary to years of reading about html, xhtml and css; though I can't find an authorative source for my previous assertion. – David Thomas Nov 21 '10 at 21:12

7 Answers7

125

You can use split like this:

alert($('#divID').attr('class').split(' ')[1]);

To get all classes, you can do this instead:

var classes = $('#divID').attr('class').split(' ');

for(var i=0; i<classes.length; i++){
  alert(classes[i]);
}

More Info:

Sarfraz
  • 377,238
  • 77
  • 533
  • 578
  • 12
    @matt , its really surprise for my how people come with solutions so fast and even complete typing the code also , people are simply brilliant in this stack overflow. I am not at at all getting stuck anywhere in my development after creating a login in stackoverflow , i gained so much knowledge in last 2 months. – kobe Nov 21 '10 at 19:55
  • I moved to UI development just few months back , I used to code a lot in backend and middle tier, This site made my UI work really easy. I would have joined earler , but no problem. – kobe Nov 21 '10 at 19:59
11
// alerts "8"
alert($('<div class="something 8"></div>').attr('class').split(' ')[1]);
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
11

This is how you would do it by referencing a div ID

$(document).ready( function () {
  alert($('#yourDivID').attr('class').split(' ')[1]);
});

The split function will allow you to split a string with the specified delimiter. This will return an array of your separated values. In this case will return an array of classnames.

Reference for split an other string methods http://www.javascriptkit.com/javatutors/string4.shtml

You should look into the following jQuery Selectors and Functions for accessing classes

Selectors

http://api.jquery.com/class-selector/ select a dom element with the specified class

http://api.jquery.com/has-selector/ select a dom element that has the specified selector

Functions

http://api.jquery.com/addClass/ method to add a class to a jQuery object

http://api.jquery.com/removeClass/ method to remove a class to a jQuery object

http://api.jquery.com/toggleClass/ method to toggle a class to a jQuery object

http://api.jquery.com/hasClass/ method to check if a jQuery object has the specified class

http://api.jquery.com/attr/ method to retreive attributes of a jQuery object

Edited: Nice cheat sheet

enter image description here

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
John Hartsock
  • 85,422
  • 23
  • 131
  • 146
6

as an alternative, it's always better practice to use the data-* html attributes to keep track of states, e.g $("div.example").data("active")

Yehia A.Salam
  • 1,987
  • 7
  • 44
  • 93
  • good advice, someone (even the coder some months later) cold switch the order of classes or add a new one, as it would make no difference in normal circumstances. – Stefan Rogin May 23 '13 at 18:12
4

You can get the value of the class attribute and split it on space.

secondClass = element.className.split(' ')[1];
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
0

This is not correct. If classes separated more than one space and you have get second class you get empty. Example:

<div class="something   fooBar"></div>
var classes = $('div').attr('class').split(' ');
alert('classes: ' + classes + '; length: ' + classes.length );
// classes: something,,,fooBar; 4 

I use the next code:

/*
 *   el  - element
 *   num - class number
 */
function getNumClass(el, num) {

  var classes = el.split(' ');
  var newclasses = [];
  var ret;

  for (var i = 0; i < classes.length; i++) {

    ret = $.trim(classes[i]);
    if(ret.length > 0) {
      newclasses.length += 1;
      newclasses[newclasses.length-1] = ret;
    }
  }

  if (num > newclasses.length) return false;

  return newclasses[num - 1];
}
skeef
  • 1
0

You can use your spilt like

alert($('#divID').attr('class').split(' ')[1]);

Then you can do this

 var classes = $('#divID').attr('class').split(' ');

for(var i=0; i<classes.length; i++){
  alert(classes[i]);
}

Source javascript split string