Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm trying to get an array of all elements with the class "sampleclass". For example, withing 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 elements that are within the "sampleclass" using javascipt and/or jQuery.

Any ideas on how to do this?

like image 421
Tomas Vinter Avatar asked Dec 21 '25 08:12

Tomas Vinter


1 Answers

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

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

* is called the All selector

EDIT: please note, in this example:

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

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

myArray contains all the sub-elements of the div: table, tr and td.

If you want all the top-level elements inside a given element, you can try:

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

This combines the child selector with the aforementioned all selector.

like image 125
Alex Bagnolini Avatar answered Dec 22 '25 20:12

Alex Bagnolini



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!