Question

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+

Was it helpful?

Solution

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...

OTHER TIPS

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") );

You have to add the div to the dom.

// Create the Div
var oDiv = document.createElement('div');
document.body.appendChild(oDiv);

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

should be

newDiv.id = "obj_1000";

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top