tags:

views:

52

answers:

3

Hi,
i try to read all classes.

HTML

<div id="test" class="fff aaa ccc" >hello world</div>

JS

if ($('#test').attr('class') != '')
{
   // Read classes
    var all_classes = $('#test').attr('class');

    // Output
    $('body').append('Classnames: '+all_classes+' ');

}

Example http://www.jsfiddle.net/AQgqU/8/

Can somebody help me?

Thanks in advance!
Peter

+3  A: 

You can do this way:

var classes = $('#test').attr('class').split(' ');

alert(classes[0]); // first class
alert(classes[1]); // second class
alert(classes[2]); // third class

Or you can use a loop:

for(var i = 0; i < classes.length; i++) {
  alert(classes[i]);
}

Update:

As suggested by @KennyTM, with above code there was possibility of space coming around a class name. You can use the $.trim function of jQuery to remove any space.

Sarfraz
I think you should `$.trim()` it and split by `/\s+/`.
KennyTM
Hi Sarfraz, thank you very much for the fast answer!
Peter
@Peter: Welcome...
Sarfraz
A: 

I took our your function() and it worked fine!

ILMV
+1  A: 

Your function works fine, but you have a syntax error at the end:

$(function()
{

    // Has the #test a Class?
    if ($('#test').attr('class') != '')
    {
       // Read classes
        var all_classes = $('#test').attr('class');

        // Output
        $('body').append('Classnames: '+all_classes+' ');

    }


}):
//^ There's a colon just here, should be a semi-colon ;

here's your fixed fiddle: http://www.jsfiddle.net/AQgqU/12/

Andy E