tags:

views:

48

answers:

1

How can I get all of the elements on a web page that have a certain class name and put them into an array? Then I want to be able to put the contents of that array in an alert box?

How can I put those elements id's into the array?

+5  A: 

If your browser supports getElementsByClassName, use that otherwise use one of the many cross-browser implementations available on the web.

Natively, you would get them as:

var elements = document.getElementsByClassName('nameOfClassHere');

This returns an array-like object, and you can traverse the elements like you would do in an array, but cannot use methods of an array on it.

If you're using a library like jQuery or MooTools, this task is made simpler for you. In jQuery to get all elements having the class name "myClass", and get their text content into a single string use,

var combinedText = $('.myClass').text();

Get id's of each matching element into an array using jQuery:

var arrayOfIDs = $('.myClass').map(function() { return this.id; }).get();

If using MooTools, you can get an array of the text content for each element that has the required class using:

var texts = $$('.myClass').get('text');

Get id's of each matching element into an array as:

var arrayOfIDs = $$('.myClass').get('id');
Anurag
To convert it to an array, you can do: `elements = Array.prototype.slice.call(elements, 0);`
Matthew Flaschen
+1 for thoroughness and examples in two libs, and noting `getElementsByClassName` does not work in every browser.
karim79
thanks for that @Matthew, does that work on IE6? thanks @karim :)
Anurag
@Anurag, converting a `NodeList` will not work on IE <= 8, in this case doesn't matters because `getElementsByClassName` also isn't supported on those versions of IE hehe, but in the case of other methods e.g. `getElementsByTagName`, will not work, and the spec mentions: *Whether the `slice` function can be applied successfully to a host object is implementation-dependent.*
CMS
@CMS I had a hunch that IE was going to be problematic here, so thanks for the full disclosure :). "Implementation-dependent" has a very specific meaning here and everywhere else this phrase is used - IE will not support it :D
Anurag