How can I get all of 开发者_StackOverflowthe 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?
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');
精彩评论