Skip to content

Instantly share code, notes, and snippets.

@mimo84
Created January 14, 2013 04:32
Show Gist options
  • Save mimo84/4527780 to your computer and use it in GitHub Desktop.
Save mimo84/4527780 to your computer and use it in GitHub Desktop.
use of forEach on HTMLCollections and arrays.
<!DOCTYPE html>
<html>
<head>
<title>forEach on HTML collections and arrays</title>
</head>
<body>
<script src="script.js"></script>
</body>
</html>
/**
* How does this script works.
* first create a new table, select all the cells with
* document.getElementsByTagName('td') or document.querySelectorAll('td')
* and then add color and some text using a forEach statement
*/
// Add the forEach method of a nodeList to HTML collections and arrays.
NodeList.prototype.forEach = HTMLCollection.prototype.forEach = Array.prototype.forEach;
// Easy to be changed to have randomHEX, just make sure the string of each color have two chars!
function randomRGB() {
var r,g,b,base=10,maximum=256;
r = intRandom(maximum,base)
g = intRandom(maximum,base)
b = intRandom(maximum,base)
return ('rgb('+ r +','+ g +','+ b +')');
}
function intRandom(max,base) {
return Math.round(max*Math.random()).toString(base);
}
function createTable(col,row) {
var i,j,t,tr,td
t=document.createElement('table')
for(i=0;i<col;i++){
var tr = document.createElement('tr')
for(j=0;j<row;j++) {
var td = document.createElement('td')
td.innerHTML = '<p>&nbsp;</p>'
tr.appendChild(td)
}
t.appendChild(tr)
}
return t
}
function colorateTable() {
var tds = document.getElementsByTagName('td')
,bgcolor
tds.forEach(function(e,i,a){
bgcolor = randomRGB()
e.style.backgroundColor = bgcolor
e.innerHTML = bgcolor
})
}
// Let's create the table
window.onload = document.body.appendChild(createTable(5,5))
// and now colorate and fill up the table
colorateTable()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment