2

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?

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.

6
  • 1
    what is the desired output Commented Jul 22, 2013 at 8:03
  • $(cls).match is wrong because .match() is defined for String type, so it should be cls = cls.match(/_\S+/g) Commented Jul 22, 2013 at 8:04
  • 1
    What is it with your nickname? Commented Jul 22, 2013 at 8:05
  • @Arun P Johny i want when other <div> has classes that begin with underScore, A condition run. Commented Jul 22, 2013 at 8:06
  • console.log(cls.replace(/_/gi,'').split(' ')); or use just split() to have array. Commented Jul 22, 2013 at 8:08

4 Answers 4

3
var classes = $("#div").attr("class").split(" ");
Sign up to request clarification or add additional context in comments.

3 Comments

damn you! :D easiest and obviously solution. After that you simply can iterate over the array and exlucde all classes without the underscore
Is this code correct? : var classes = $("#div").attr('class').match(/_\S+/g).split(' ')
No, becouse "".match() returns array. You can't split array.
2

Use split() function:

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

Comments

1

You can easily do it in plain js:

document.getElementById('div').classList;

will give you the list of classes

Comments

0

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

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

}else{

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

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.