How can I get an array of all elements in a specific class using javascript and / or jQuery?

I am trying to get an array of all elements with class "sampleclass". For example, with my document, I have three divs:

<div class="aclass"></div>
<div class="sampleclass"></div>
<div class="anotheraclass"></div>
<div class="sampleclass"></div>

I want to get an array with all the elements in the "sampleclass" using javascipt and / or jQuery.

Any ideas on how to do this?

+3
source share
4 answers

This will get all the elements inside each element containing the class sampleclass:

var myArray = $('.sampleclass *');

*called All selector

EDIT : note that in this example:

<div id="test">
   <table>
      <tr><td>TEST</td></tr>
   </table>
</div>

var myArray = $('#test *');

myArrayIt contains all of the sub-div: table, trand td.

, , :

var myArray = $('#test > *');

.

+3
$( '.sampleclass' );

each.

+1

......

$('.sampleclass').........

Next, you can iterate through it with the eachfollowing:

$('.sampleclass').each(function(){
  // more code........
})

And finally, you can also get each individual element:

$('.sampleclass')[0]; // first
$('.sampleclass')[1]; // second
// and so on........
+1
source

Extension of Jacob Relkin's answer:

$('.sampleClass').each(function()
{
   // do something with it...
   $(this).css('background-color', 'green');
});
0
source

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


All Articles