javascript - What do querySelectorAll, getElementsByClassName and other getElementsBy* methods return? -


do getelementsbyclassname (and similar functions getelementsbytagname , queryselectorall) work same getelementbyid or return array of elements?

the reason ask because trying change style of elements using getelementsbyclassname. see below.

//doesn't work document.getelementsbyclassname('myelement').style.size = '100px';  //works document.getelementbyid('myidelement').style.size = '100px'; 

your getelementbyid() code works since ids have unique , function returns 1 element (or null if none found).

however, getelementsbyclassname(), queryselectorall(), , other getelementsby* methods return array-like collection of elements. iterate on real array:

var elems = document.getelementsbyclassname('myelement'); for(var = 0; < elems.length; i++) {     elems[i].style.size = '100px'; } 

if prefer shorter, consider using jquery:

$('.myelement').css('size', '100px'); 

Comments

Popular posts from this blog

'hasOwnProperty' in javascript -

How to put a lock and transaction on table using spring 4 or above using jdbcTemplate and annotations like @Transactional? -

How to understand 2 main() functions after using uftrace to profile the C++ program? -