views:

342

answers:

5

I think this is specific to IE 6.0 but...

In javascript I add a div to the dom...I assign an ID attribute. When I later try to pick up the Div by the ID all I get is null???

Any suggestions?

Example:

var newDiv = document.createElement("DIV"); newDiv.setAttribute("ID", "obj_1000"); document.appendChild(newDiv);

alert("Added:" + newDiv.getAttribute("ID") + ":" + newDiv.id + ":" + document.getElementById("obj_1000") );

Alert prints "::null"

Seems to work fine in Firefox 2.0+

+1  A: 

You have to add the div to the dom.

// Create the Div
var oDiv = document.createElement('div');
document.body.appendChild(oDiv);
David Basarab
+3  A: 

The div needs to be added to an element for it to be part of the document.

document.appendChild(newDiv);

alert( document.getElementById("obj_1000") );
Ben Scheirman
A: 

newDiv.setAttribute( "ID", "obj_1000" );

should be

newDiv.id = "obj_1000";

harpo
+7  A: 

In addition to what the other answers suggest (that you need to actually insert the element into the DOM for it to be found via getElementById()), you also need to use a lower-case attribute name in order for IE6 to recognize it as the id:

var newDiv = document.createElement("DIV"); 
newDiv.setAttribute("id", "obj_1000");
document.body.appendChild(newDiv);

alert("Added:"
   + newDiv.getAttribute("id") 
   + ":" + newDiv.id + ":" 
   + document.getElementById("obj_1000") );

...responds as expected:

Added:obj_1000:obj_1000:[object]


According to the MSDN documentation for setAttribute(), up to IE8 there is an optional third parameter that controls whether or not it is case sensitive with regard to the attribute name. Guess what the default is...

Shog9
A: 

Hummm, thanks for putting me on the right track guys...this was odd but it turns out that if I change the case to lower case, everything starting working just fine...

Finished Result:

var newDiv = document.createElement("DIV");

newDiv.setAttribute("id", "obj_1000");

document.appendChild(newDiv);

alert("Added:" + newDiv.getAttribute("id") + ":" + newDiv.id + ":" + document.getElementById("obj_1000") );

ODD...VERY ODD

Markus
Very odd? No, very IE.
Jason Bunting