Using document.getElementsByTagName

This is an example of using document.getElementsByTagName.
Clicking on the button below should change the color of the text and background of all the "div" elements on the page.

JavaScript code

// This code is contained in the head element or an external file // This function randomly returns a hex digit: 0-9,A-F function getRandomHexDigit() { return ["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"][Math.floor(Math.random() * 16)]; } // This function returns a random color in hex with a preceding # sign function getRandomColor() { var color = "#"; for (var i=0; i<6; i++) color += getRandomHexDigit(); return color; } // This function changes the text and background color of all div elements function changeElements() { var elems document.getElementsByTagName("div"); for (var i=0; i<elems.length; i++) { elems[i].style.color = getRandomColor(); elems[i].style.backgroundColor = getRandomColor(); } } // This function sets up the event handler for the button function init() { document.getElementById("ChangeButton").onclick = changeElements; } // This line sets the initialization code to run after the body is done loading window.onload = init;