I'm trying to find out how to retrieve the second class name of a class attribute.
<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.
Using the JavaScript getElementByClassName() method: The JavaScript getElementsByClassName is used to get all the elements that belong to a particular class.
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.
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];
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.
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:
// alerts "8" alert($('<div class="something 8"></div>').attr('class').split(' ')[1]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With