RGA
RGA

Reputation: 612

Dynamic Array undefined error in IE

I have tried to generate dynamic Control. It is working on FF but IE gives error:

divcntrl[i] is undefined.

Please check the following code:

 var mc=document.getElementById("maindiv");
    var divcntrl = new Array();
    for(var i=0; i<10;i++) {
      divcntrl[i]=document.createElement("div");\\error here
    divcntrl[i].setAttribute("id","div"+ i);
      mc.appendChild(divcntrl[i]);
}

Upvotes: 0

Views: 217

Answers (3)

epascarello
epascarello

Reputation: 207501

There is no such thing as <div1> element. Running your code in a fiddle, it runs without errors so the problem is somewhere else. Are you cached with a bad version of the file?

var mc=document.getElementById("maindiv");
var divcntrl = new Array();
for(var i=0; i<10;i++) {
    divcntrl[i]=document.createElement("div");
    divcntrl[i].innerHTML = i;
    mc.appendChild(divcntrl[i]);
}​

I think you would want to code it more like

var mc = document.getElementById("maindiv");
var divcntrl = [];
for (var i=0; i<10; i++) {
    var div = document.createElement("div");
    div.id = "div" + i;
    div.innerHTML = i;
    divcntrl.push(div);
    mc.appendChild(div);
}​

Upvotes: 1

omerkirk
omerkirk

Reputation: 2527

The problem is with this line

divcntrl[i]=document.createElement("div" + i);

Just try this:

var divElt = document.createElement("div");
divElt.id = i;
divcntrl[i] = divElt;

Upvotes: 0

ContentiousMaximus
ContentiousMaximus

Reputation: 1304

You can create a DIV element, NOT a "div"+i element, since "div"+i is not part of any HTML specification ("div1" is not an HTML element). Are you confusing "div" and "id"?

Upvotes: 0

Related Questions