Skip to content Skip to sidebar Skip to footer

Get The "class" Attribute Of An Object Split Into An Array Of Strings

Preamble: I'm Italian, sorry for my bad English. So this is the question: considering an HTML object like this:
how can I

Solution 1:

You need # for id selector and use split() to get array from string.

Live Demo

var a = $('#myDiv').attr('class').split(' ');

You can iterate through array using jQuery jQuery.each() of for loop.

var a = $('#myDiv').attr('class').split(' ');

$.each(a, function(index, item){
    alert(item);
});​

Solution 2:

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/

Solution 3:

Why don't you try this: http://jsfiddle.net/egZ2z/

var cls = $('#myDiv').attr('class');
var n = cls.split(' ')
alert(n);

Post a Comment for "Get The "class" Attribute Of An Object Split Into An Array Of Strings"