Naor
Naor

Reputation: 24053

get class name with jquery

Inside the div element set within variable called $target I have elements with single class. I want to pass throw each element and get its class name. Something like this:

$.each($target.children(), function(){
    //get class from 'this' - how?
});

What is the best way to do so?

I don't want to do it using classic JavaScript (.className)!

Upvotes: 5

Views: 6379

Answers (3)

Ken Redler
Ken Redler

Reputation: 23943

Here's one way to do it that handles multiple classes per element, returns a list of classes without duplicates, and should work across browsers (using $.inArray instead of indexOf).

function getUniqueClasses(jqobj) {
  var result = [];
  jqobj.each(function(idx, elem) {
    $.each(elem.className.split(' '), function(i, e) {
      if ($.inArray(e, result) == -1) result.push(e);
    });
  });
  return result.join(','); // if you want a list instead of an array
}

Then:

var answer = getUniqueClasses( $('#target').children() );

Upvotes: 1

Chandu
Chandu

Reputation: 82893

Use attr function. e.g.

$.each($target.children(), function(){
    alert($(this).attr("class"))
});

Upvotes: 5

RAMe0
RAMe0

Reputation: 1257

$.each($target.children(), function(){
    var cls = $(this).attr("class");
});

Upvotes: 0

Related Questions