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)!
Use attr function. e.g.
$.each($target.children(), function(){
alert($(this).attr("class"))
});
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() );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With