Get the “class” attribute of an object split into

2019-07-10 03:49发布

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.

3条回答
Emotional °昔
2楼-- · 2019-07-10 04:09

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);
});​
查看更多
贪生不怕死
3楼-- · 2019-07-10 04:13

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/

查看更多
Bombasti
4楼-- · 2019-07-10 04:18

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

var cls = $('#myDiv').attr('class');
var n = cls.split(' ')
alert(n);
查看更多
登录 后发表回答