views:

33

answers:

5

Hi How can I get hold of elements within a Div that uses a class say "sample"?

There are many Div's in the document

<div class="sample"/>
..
<div class="sample"/>
..
<div class="sample"/>
..
<div id = "samplediv">
  <div class="sample">
  <div>
</div>

My question was to find the div with class sample and manipulate some properties of this div. So I want to get hold of the Div with class = "sample"?

+1  A: 

If you're using jQuery, you can just use the equivalent CSS selector, in this case:

$(".sample")
kekekela
Please find my question updated
SARAVAN
+2  A: 

In most modern browsers, you can get objects by class name using the function:

getElementsByClassName("sample")

This is available on any element, including document (as in document.getElementsByClassName). Problem is, older browsers don't support this. Instead, you can use jQuery to do the same thing:

$(".sample")

Hope this helps!

mattbasta
Please find my question updated
SARAVAN
SARAVAN: To manipulate one of the elements with the class "sample", you'll simply: `document.getElementsByClassName("sample")[0]` to retrieve the element. So for instance, to set the background to red, you'd `document.getElementsByClassName("sample")[0].style.backgroundColor = "red"`
mattbasta
A: 

if you can use jQuery you can do this by:

jQuery("div.sample");
sushil bharwani
Please find my question updated
SARAVAN
jQuery("div.sample").each(function(n){ jQuery(this).property u want to modify for individual array element;});
sushil bharwani
+2  A: 

With jQuery:

$('.sample').each(function() { doStuff($(this)); });

Or in plain JS:

document.getElementsByClassName('sample');
Coronatus
Please find my question updated
SARAVAN
Still works for multiple elements.
Coronatus
A: 

I voted up drachenstern`s comment so...

if you use Prototype.js you can use function $$(selector) like:

$$('#sourceDivId .sample').each(function(elem){ 
// do stuff
});

;)

chapluck