View Full Version : Accessing dynamically created elements

12-23-2010, 10:03 AM

I'm trying to write a script for a website that reads from a database and makes a separate table for each entry in the database. Since the number of entries can change, I want to dynamically create a div for each one, which I can later hide or display based on user selection. However, when I try to access the dynamically created elements by their ID, they return null.

Is what I'm trying to do here actually possible?

for(var i = 0; i < tables.length; i ++)
var newDiv = document.createElement("div");
newDiv.setAttribute("id", tables[i].name);
newDiv.setAttribute("name", tables[i].name);
newDiv.setAttribute("class", "hidden");
newDiv.innerHTML += tables[i].name;
newDiv.innerHTML += "<table id = 'table"+tables[i].name+"' border = '1'>";
newDiv.innerHTML += "<tr>";

for(var rows = 0; rows < table.arrayOfFields.length; rows++)
numOfEntries = table.arrayOfFields[rows].arrayOfEntries.length;


for(var cols = 0; cols < numOfEntries; cols++)

for(var rows = 0; rows < table.arrayOfFields.length; rows++)





12-23-2010, 10:13 AM
innerHTML is not a standard DOM method. Moreover, in some cases (for instance in IE when it's about TABLE or TABLE elements) innerHTML is readonly.

use DOM methods to create the table, same as you did with your div (createElement, setAttribute, and so on)

Some notes regarding your code:
1. The name attribute is to be used only in case of some elements( mainly forms or forms elements). DIV is not among them. Nor TABLE. A DIV or a TABLE can not bear a name, Anyway, what's the use? id should be enough.

2. IE has some particular behaviors regarding setting some attributes with setAttribute(). For instance: class.To avoid a double code, use DOM 0 crossbrowser syntax: