Use of the native javascript forEach


The forEach method in JavaScript is a standard from the new ECMA5 script specifications.
It can be used as it is if the applied to a node list, such as something returned from a function like document.querySelectorAll(”) or document.getElementById(‘id’).
The whole point of this trick it’s this one:

NodeList.prototype.forEach = HTMLCollection.prototype.forEach = Array.prototype.forEach;

We add the forEach prototype method to HTML collections and arrays.

So I have prepared a simple script that generates a table and colorize the table using the native forEach method.

/**
* 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
//let's use our forEach!
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()

You can download the code from here.


Lascia un commento!