Your code works fine, however you are testing the values or your assumptions about what should be stored is erroneous. (example: http://jsbin.com/tanesicoti/1/edit?js,console).
However it is very inefficient for what it does. A better way to write it in a single loop, and without having to search the DOM afterwards is like so (http://jsbin.com/zozocikanu/2/edit?js,console):
var can = [], ctx = [];
/*
* Create a node in memory so that we can store the elements inside it
*/
var canvasFragment = document.createDocumentFragment();
var divFragment = document.createDocumentFragment();
/*
* Initialise our loop variables
*/
var canvasCount = 256;
var canvas;
var div;
for (var i = 0; i < canvasCount; i++) {
/*
* Create a canvas element and insert it into its fragment
*/
canvas = document.createElement('canvas');
canvas.width = canvas.height = 8;
canvas.setAttribute('id', 'canvas' + i);
canvasFragment.appendChild(canvas);
/*
* Create a div element and insert it into its fragment
*/
div = document.createElement('div');
div.setAttribute('id', 'chr' + i);
divFragment.appendChild(div);
/*
* Get our array values, objects are passed by reference so
* even though our elements aren't in the DOM yet, this variable
* will point to the same item after we do.
*/
can[i] = canvas;
ctx[i] = canvas.getContext('2d');
}
/*
* Insert our items into the DOM. This is much faster as the browser
* has to repaint when you insert items, but as we insert them in two
* actions and not 512 (2 * 256) we create 2 repaints and not 512.
*/
document.body.appendChild(canvasFragment);
document.body.appendChild(divFragment);
console.log(ctx[123], ctx.length);
can[i]
? Is there any error in JS console? Try if value ofdocument.getElementById
is notnull
.