如何将元素的类转换为数组?

时间:2021-11-19 13:41:34

i have a <div> like this.

我有一个像这样的

<div id="div" class="a b _c d _e f"></div>

how can convert classes of <div> to a javaScript array?

如何将

的类转换为javaScript数组?

var cls = $('#div').attr('class');
cls = $(cls).match(/_\S+/g).join(" "); //separate classes are begin with underScore.
cls = $(cls).toArray();

but this doesn't work.

但这是行不通的。

4 个解决方案

#1


2  

Use split() function:

使用分割()函数:

var array;
array = $('#div').attr('class').split(' ');

#2


3  

var classes = $("#div").attr("class").split(" ");

#3


1  

You can easily do it in plain js:

你可以用简单的js轻松做到:

document.getElementById('div').classList;

will give you the list of classes

会给你类的列表吗

#4


0  

if($('#div').hasClass('old_class')){

如果($(' # div ').hasClass(old_class)){

$('#div').removeClass('old_class').addClass('new_Class');

$(' # div ').removeClass(old_class).addClass(“new_Class”);

}else{

其他} {

$('#div').removeClass('new_class').addClass('old_Class');

$(' # div ').removeClass(new_class).addClass(“old_Class”);

}

}

#1


2  

Use split() function:

使用分割()函数:

var array;
array = $('#div').attr('class').split(' ');

#2


3  

var classes = $("#div").attr("class").split(" ");

#3


1  

You can easily do it in plain js:

你可以用简单的js轻松做到:

document.getElementById('div').classList;

will give you the list of classes

会给你类的列表吗

#4


0  

if($('#div').hasClass('old_class')){

如果($(' # div ').hasClass(old_class)){

$('#div').removeClass('old_class').addClass('new_Class');

$(' # div ').removeClass(old_class).addClass(“new_Class”);

}else{

其他} {

$('#div').removeClass('new_class').addClass('old_Class');

$(' # div ').removeClass(new_class).addClass(“old_Class”);

}

}