Put elements by class name in an array and warn about it with Javascript

How can I get all the elements on a webpage with a specific class name and put them in an array? Then I want to be able to place the contents of this array in a warning window?

How can I put these elements in an array?

+4
source share
1 answer

If your browser supports getElementsByClassName , use one of the many cross-browser versions available on the Internet otherwise.

Naturally you will receive them as:

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

This returns an object that looks like an array, and you can move the elements as you would in an array, but you cannot use the array methods on it.

If you use jQuery or MooTools library, this task is simplified for you. In jQuery, to get all the elements with the class name "myClass" and get their text content in one line use

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

Get the identifier of each corresponding element in an array using jQuery:

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

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

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

Get the identifier of each corresponding element in an array as:

 var arrayOfIDs = $$('.myClass').get('id'); 
+7
source

All Articles