3

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?

2
  • 1
    Just to clarify - which browsers do you need to support? JQuery should support most, some DOM methods dont work across the board. 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. Commented Mar 29, 2010 at 11:17

4 Answers 4

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 combines the child selector with the aforementioned all selector.

Sign up to request clarification or add additional context in comments.

Comments

1
$( '.sampleclass' );

You can then iterate through the array with each.

1 Comment

What Jacob said. Alternately, without jQuery, document.getElementsByClassName('sampleclass');
1

......

$('.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........

7 Comments

-1 for just copy-paste the other 2 answers. Also, that last bit of code is terrible for performance -- CACHE the result.
@Coronatus: it is ridiculouse that you said copy-paste. My ansewr was posted before yours. This is very basic thing for me, so i don't need to copy-paste. Go to my blog to know my jquery skills just by going through my profile or even have a lookt at my SO answers in jquery tag. Consider your vote again....Thanks
moderator should take notice of this please.
@Coronatus: What do you mean please, any consideration to what you did?
|
0

Expanding Jacob Relkin' answer:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.