Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get class name with jquery

Tags:

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)!

like image 233
Naor Avatar asked Dec 25 '10 17:12

Naor


2 Answers

Use attr function. e.g.

$.each($target.children(), function(){
    alert($(this).attr("class"))
});
like image 59
Chandu Avatar answered Oct 23 '22 02:10

Chandu


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() );
like image 45
Ken Redler Avatar answered Oct 23 '22 03:10

Ken Redler