Charles Yeung
Charles Yeung

Reputation: 38805

jQuery get multiple class name and convert them to an array

Suppose I have an element look likes

<div class="amy mary peter john tom">abc</div>

I will use the jQuery to get the class name

var classname = $(div).attr('class');

Since the result is "amy mary peter john tom", how can I convert this string to array?

Somethings likes var classname = ["amy", "mary", "peter", "john", "tom"];

Thanks

Upvotes: 3

Views: 6447

Answers (2)

Andoy Abarquez
Andoy Abarquez

Reputation: 1149

for Example : you have : and you want to get the 'class2'

just add this. hope will help this. $('div').attr('class').split(' ')[1];

Upvotes: 1

Emmett
Emmett

Reputation: 14327

Use the string split function:

var classname = $('div').attr('class').split(/\s+/);

Upvotes: 8

Related Questions