开发者

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

开发者 https://www.devze.com 2022-12-24 06:32 出处:网络
I\'m trying to get an array of all elements with the class \"sampleclass\". For example, withing my document I have three divs:

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 ide开发者_StackOverflow中文版as on how to do this?


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.


$( '.sampleclass' );

You can then iterate through the array with each.


......

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

Further you can iterate over it using each like this:

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

And finally, you can get each individual item like this too:

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


Expanding Jacob Relkin' answer:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号