Get class name with jquery

Inside the div element specified in a variable named $ target, I have elements with one class. I want to pass each element and get its class name. Something like that:

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

What is the best way to do this?

I do not want to do this using classic JavaScript (.className)!

+4
source share
3 answers

Use the attr function. eg.

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

Here is one way to do this, which processes several classes for each element, returns a list of classes without duplicates, and should work in different 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() ); 
+1
source
 $.each($target.children(), function(){ var cls = $(this).attr("class"); }); 
0
source

Source: https://habr.com/ru/post/1333348/


All Articles