Created
January 14, 2013 04:32
-
-
Save mimo84/4527780 to your computer and use it in GitHub Desktop.
use of forEach on HTMLCollections and arrays.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>forEach on HTML collections and arrays</title> | |
</head> | |
<body> | |
<script src="script.js"></script> | |
</body> | |
</html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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> </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