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?
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?
Share Improve this question edited Sep 4, 2010 at 1:57 OOProg asked Sep 4, 2010 at 1:44 OOProgOOProg 1891 gold badge5 silver badges16 bronze badges 01 Answer
Reset to default 7If 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 binedText = $('.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');