How to select first class in a list of class definition for an element
I have these elements :
<div id="contentoDinamico">
<div id="item_box_3777" class="index0 itemContenutoDinamico attivo">
<div id="item_box_3792" class="index4 itemContenutoDinamico">
</div>
and this function :
开发者_StackOverflow$("#contentoDinamico div").attr('class', function(i, e) {
a.push(e);
});
but I'd like to push only first class for each div child;
so, in the example, index0
and index4
, not index0 itemContenutoDinamico attivo
and index4 itemContenutoDinamico
.
How can I do this?
HTML5 compatible browsers add a classList
property to elements which you can index directly. Alternatively you'd have to split the class value by space characters:
$("#contentoDinamico div").each(function(i, e) {
if ('classList' in this) {
a.push(this.classList[0]);
} else {
var cn = this.className;
var ca = cn.split(' ');
a.push(c[0]);
}
}
The space splitting version might break if you have leading spaces in your class attribute.
Split the class that you return by a space, and then there you have it:
.split(/\s/)
精彩评论