How to get the second class name from element?

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


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:

  • http://www.w3schools.com/jsref/jsref_split.asp

// alerts "8"
alert($('<div class="something 8"></div>').attr('class').split(' ')[1]);

Tags:

Jquery

Class