Pepe
Pepe

Reputation: 1002

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');
});

Upvotes: 0

Views: 170

Answers (2)

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>

Upvotes: 2

aleks korovin
aleks korovin

Reputation: 744

If you want to get a list of class names of items please update your code a bit:

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

console.log(ClassNames);
<ul id="list">
  <li class="names list-item"></li>
</ul>

Upvotes: 2

Related Questions