Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get "class" names of all specific divs

Whats wrong with my each function? At this way, I get all data, not just the class name:

var ClassNames = $("#list .names").each(function() {
   $(this).attr('class');
});

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You could look into .map() like this example:

var ClassNames = $("#list .names").map(function() {
   return $(this).attr('class');
}).get();

You had 2 problems, one being you are not using return inside your function. Second even with return, .each would still return the elements and not the class’

Demo

var ClassNames = $("#list .names").map(function() {
   return $(this).attr('class');
}).get();

console.log(ClassNames)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="list">
  <div class="names test1"></div>
  <div class="names test2"></div>
  <div class="names test3"></div>
  <div class="names test4"></div>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading