Peter
Peter

Reputation: 11835

Jquery - Read all Classes from a div

I'm trying to read all class names from HTML element in the following way. But it doesn't work:

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?

Upvotes: 3

Views: 12323

Answers (2)

Sarfraz
Sarfraz

Reputation: 382746

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.

Upvotes: 15

Andy E
Andy E

Reputation: 344585

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/

Upvotes: 2

Related Questions