5

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

2
  • 1
    possible duplicate of jquery - get class of clicked li element Commented Dec 25, 2010 at 17:30
  • It is not duplication. Different questions. Commented Dec 25, 2010 at 17:43

3 Answers 3

5

Use attr function. e.g.

$.each($target.children(), function(){
    alert($(this).attr("class"))
});
Sign up to request clarification or add additional context in comments.

2 Comments

Does it returns array of class names or single string with the class names?
It will retirn single string with class names.
1

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() );

Comments

0
$.each($target.children(), function(){
    var cls = $(this).attr("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.