Preamble: I'm Italian, sorry for my bad English.
So this is the question:
considering an HTML object like this:
<div id="myDiv" class="c1 c2 c3 c4 c5"></div>
how can I get an array of strings, using jquery, from the "class" attribute of the "div" element?
Example:
var a = $('#myDiv').getClassArray(); //Not working,just an example
return a; //[c1,c2,c3,c4,c5]
I thought I could read the "class" attribute and then split the string, but it seems too verbose, I wondered if there was a shorter and more elegant method.
You need
#
for id selector and use split() to get array from string.Live Demo
You can iterate through array using jQuery jQuery.each() of for loop.
The new standard
classList
property would allow such easy access on DOM elements (e.g., through$('#myDiv')[0].classList
in jQuery), but it is not universally implemented. See here for documentation on this standard or here for current browser support.Providing such functionality as a shim was proposed for jQuery in bug 7378, but was rejected.
You could however, get such support via a shim, such as perhaps https://github.com/eligrey/classList.js
Updated: A demo with the shim is at http://jsfiddle.net/brettz9/WWs5B/1/
Why don't you try this: http://jsfiddle.net/egZ2z/