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+
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+
Share Improve this question edited Feb 18, 2020 at 13:47 Awais 4,9124 gold badges19 silver badges42 bronze badges asked Sep 9, 2008 at 20:07 MarkusMarkus 1,5571 gold badge19 silver badges22 bronze badges5 Answers
Reset to default 8In 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...
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