How can I get an array of all elements within a specific class using javascript andor jQuery? - Stack Overflow

I'm trying to get an array of all elements with the class "sampleclass". For example, wi

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?

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?

Share Improve this question edited Mar 29, 2010 at 11:14 Péter Török 116k31 gold badges277 silver badges331 bronze badges asked Mar 29, 2010 at 11:12 Tomas VinterTomas Vinter 2,6919 gold badges36 silver badges45 bronze badges 2
  • 1 Just to clarify - which browsers do you need to support? JQuery should support most, some DOM methods dont work across the board. – Russell Commented Mar 29, 2010 at 11:16
  • You want all the elements INSIDE the sampleclass element? If yes then there is a typo in the question, and most people have answered wrong. – Alex Bagnolini Commented Mar 29, 2010 at 11:17
Add a ment  | 

4 Answers 4

Reset to default 3

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745219985a4617204.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信