Diodeus 的答案是正确的,但是如果你想在没有JQuery 的情况下这样做(上帝帮助你),你只需要一个用于 getElementsByClassName() 的 polyfill:
来自https://gist.github.com/eikes/2299607
// Add a getElementsByClassName function if the browser doesn't have one
// Limitation: only works with one class name
// Copyright: Eike Send http://eike.se/nd
// License: MIT License
if (!document.getElementsByClassName) {
document.getElementsByClassName = function(search) {
var d = document, elements, pattern, i, results = [];
if (d.querySelectorAll) { // IE8
return d.querySelectorAll("." + search);
}
if (d.evaluate) { // IE6, IE7
pattern = ".//*[contains(concat(' ', @class, ' '), ' " + search + " ')]";
elements = d.evaluate(pattern, d, null, 0, null);
while ((i = elements.iterateNext())) {
results.push(i);
}
} else {
elements = d.getElementsByTagName("*");
pattern = new RegExp("(^|\\s)" + search + "(\\s|$)");
for (i = 0; i < elements.length; i++) {
if ( pattern.test(elements[i].className) ) {
results.push(elements[i]);
}
}
}
return results;
}
}
然后您可以正常使用 getElementsByClassName :
var elements = document.getElementsByClassName('myClass');
for(var i = 0; i < elements.length; i++) {
if(elements[i].checked) {
//do something here.
}
}
您需要选择的每一个元素都myClass
适用于:class="myClass"
或class="something something myClass"
.