admin管理员组文章数量:1315966
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');
本文标签: Put elements by class name in an array and alert it with JavascriptStack Overflow
版权声明:本文标题:Put elements by class name in an array and alert it with Javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741995130a2409888.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论