最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Put elements by class name in an array and alert it with Javascript - Stack Overflow

programmeradmin1浏览0评论

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 0
Add a ment  | 

1 Answer 1

Reset to default 7

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 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');
发布评论

评论列表(0)

  1. 暂无评论