javascript creating dom nodes then searching for them

KingKaeru

Supreme [H]ardness
Joined
Jul 16, 2000
Messages
6,465
Can anyone get this to work? I've been pulling my hair out trying to find elements after I create them.

Code:
<script type="text/javascript">
  node = document.createElement("div");
  node.id = "myNode";
  
  // try and find the node
  if(document.getElementById("myNode")) {
    alert('node found');
  } else {
    alert("node not found");
  }
  
</script>
 
I was able to get it to work with the following:

Code:
<html>
<head>
<script type="text/javascript">
function init() {
  node = document.createElement("div");
  node.id = "myNode";

  document.body.appendChild(node);

  alert(node);
  
  // try and find the node
  if(document.getElementById("myNode")) {
    alert('node found');
  } else {
    alert("node not found");
  }
}  
</script>
</head>
<body onload="init()">
</body>
</html>

According to this, it looks like he node has to be added to the DOM before you can get it by getElementById.

Also, it looks like the whole page has to load before the script will work. If you remove the onload="init()" from the body tag, then remove the move the logic in init() to outside of the function, you'll see "node not found".
 
or instead of <body onload="init()"> you can try this after this init() function:

Code:
if (window.attachEvent) window.attachEvent("onload", init);
else window.onload = function() { init(); }
its untested but I've used similar code with great success
 
If you create an element, you have to append it to the document somewhere before you can search for it in the document.

Code:
window.onload = function() {
    var div = document.body.appendChild(document.createElement("div"));
    alert(div.parentNode);
};

However, if you append it to the document, you'll already have a reference to the element, so no need to search by id for it (unless you're doing stuff with innerHTML that might screw up the reference).
 
Back
Top