You can't use getElementById to access elements added by a script. It can see only the original ID list present at the time the page loads.
MidiMagic
Nearly a Senior Poster
3,319 posts since Jan 2007
Reputation Points: 730
Solved Threads: 182
> You can't use getElementById to access elements added by a script.
Bosh. Please verify the facts before stating something.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv"Script-Content-Type" content="text/javascript">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="Expires" content="0"> <!-- disable caching -->
<title>Example</title>
<script type="text/javascript">
function addElem(frm) {
if(!frm)
return;
var d = document.createElement("DIV");
d.id = "thirdDiv";
d.innerHTML = "ThirdDiv";
frm.appendChild(d);
}
function showDiv(frm) {
if(!frm)
return;
var divs = document.getElementsByTagName("DIV");
if(!divs)
return;
for(var i = 0, maxI = divs.length; i < maxI; ++i) {
alert("DIV-" + (i + 1) + ": " + divs[i].id);
}
}
function showNewDiv(frm) {
if(!frm)
return;
var e = document.getElementById("thirdDiv");
if(e) {
alert("The ID of newly added DIV is: " + e.id);
} else {
alert("First click on the 'Add DIV' button");
}
}
</script>
</head>
<body>
<form id="frm" name="frm" action="#">
<div id="firstDiv">FirstDiv</div>
<div id="secondDiv">SecondDiv</div>
<input type="button" value="Add DIV" onclick="addElem(this.form);">
<input type="button" value="Show all DIV's" onclick="showDiv(this.form);">
<input type="button" value="Show new DIV" onclick="showNewDiv(this.form);">
</form>
</body>
</html>
> amongst a host of other hopeless stabs in the dark!!
> Eternally grateful for any pointers, even if it's to say that i can't do it!
You can try using Closures which are inner functions which can be executed even outside the context of it's enclosing function. Something like:
// Here 'id' is the ID of the element passed to the showDetails function
xmlHttp.onreadystatechange = function(myId) {
return function() {
if(xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
document.getElementById(myId).innerHTML=xmlHttp.responseText;
}
}
}(id);
~s.o.s~
Failure as a human
11,938 posts since Jun 2006
Reputation Points: 3,281
Solved Threads: 733