function color(element) { element.style.backgroundColor = 'red' ; } var elem = document.getElementsByTagName("div"); var Length = elem.length; for(i=0; i<Length; i++){ elem[i].onclick = function() {color(this)}; }