Home > database >  Get "class" names of all specific divs
Get "class" names of all specific divs

Time:11-24

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

CodePudding user response:

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

Show code snippet

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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related