Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

<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.

like image 732
benVG Avatar asked Jan 31 '26 18:01

benVG


2 Answers

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);
});​
like image 167
Adil Avatar answered Feb 02 '26 10:02

Adil


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/

like image 45
Brett Zamir Avatar answered Feb 02 '26 10:02

Brett Zamir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!