Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the second class name from element?

Tags:

jquery

class

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.

like image 728
CyberJunkie Avatar asked Nov 21 '10 19:11

CyberJunkie


People also ask

How do you find the class of an element?

Using the JavaScript getElementByClassName() method: The JavaScript getElementsByClassName is used to get all the elements that belong to a particular class.

How do you select an element with the class name?

class selector selects elements with a specific class attribute. To select elements with a specific class, write a period (.) character, followed by the name of the class.

How do I find the first element of a class name?

If you want only the first element in the DOM with that class, you can select the first element out of the array returned. var elements = document. getElementsByClassName('className'); var requiredElement = elements[0];

How do you find an element with multiple classes?

Use the getElementsByClassName method to get elements by multiple class names, e.g. document. getElementsByClassName('box green') . The method returns an array-like object containing all the elements that have all of the given class names.


2 Answers

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
like image 183
Sarfraz Avatar answered Oct 28 '22 23:10

Sarfraz


// alerts "8" alert($('<div class="something 8"></div>').attr('class').split(' ')[1]); 
like image 24
Matt Ball Avatar answered Oct 29 '22 01:10

Matt Ball