Your getElementById()
code works since IDs have to be unique and thus the function always returns exactly one element (or null
if none was found).
However, getElementsByClassName()
, querySelectorAll()
, and other getElementsBy*
methods return an array-like collection of elements. Iterate over it like you would with a real array:
var elems = document.getElementsByClassName('myElement');
for(var i = 0; i < elems.length; i++) {
elems[i].style.size = '100px';
}
If you prefer something shorter, consider using jQuery:
$('.myElement').css('size', '100px');
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…