What is difference between querySelectorAll and getElementsBy* methods ?

Ask a question+

The reason I ask is that I am trying to change the style of all elements using getElementsByClassName. See below.

//doesn't work
document.getElementsByClassName('myElement').style.size = '100px';

document.getElementById('myIdElement').style.size = '100px';
add comment

1 Answer


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';
Hayk Hovsepyan 650
add comment

Your Answer