How to register DOM id when writing objects dynamically in javascript?

Go To


I have a problem with this script. At first I had the <div>s hard-coded and it was working fine. But then I needed to alter the navigation bar dynamically because I changed the (number of) links.

The problem is that the id's are not registering when they are injected with element.innerHTML = (html string).

How can I fix this?

Here is the code:


 function constructNav() {
   var submenu_layer_innerHTML = "";
   var top_nav_innerHTML = "<UL class=\"nav_category\">";
   for (i=0; i<links.length; i++) {
     submenu_layer_innerHTML = "<div class=\"submenu\" id=\"submenu" + i + "\" onMouseOut=\"timeHideNav('" + i + "','1000')\"> </div>";
     top_nav_innerHTML += "<LI id=\"link" + i + "\"><a href=# onMouseOver=\"expandNav('" + i + "');\">" + links[i] + "</a></LI>";
   top_nav_innerHTML += "</UL>";
   document.getElementById("top_nav").innerHTML = top_nav_innerHTML;
   document.getElementById("submenu_layer").innerHTML = submenu_layer_innerHTML;


<script type="text/javascript" src="scripts.js"> </script>
<script type="text/javascript">
var links =["link 1",
    "link 2",
    "link 3",
    "link 4",
    "link 5",
    "link 6"];

<body onLoad="constructNav();">

<div id="submenu_layer"> </div>
<div id="top_nav"> </div>

I'm getting this error in firefox:

  line 35: document.getElementById("submenu"+pageNo) is NULL
2012-04-03 21:51
by Ozzy
it works fine in my firefox 11.0, all of the elements have IDs. (link0~ link5, submenu5 - XXX 2012-04-03 22:10
i get this error in firefox: document.getElementById("submenu"+pageNo) is NULL

that started when I changed <div id="submenu1"></div> (10 of those) to 6 of those dynamically generated in javascript - Ozzy 2012-04-03 22:15


You are overwriting submenu_layer_innerHTML during each iteration of the for loop. Make sure to use +=.

2012-04-03 22:13
by gilly3
lool i can't believe that was it :/. feel like an idiot now. in my defence i'm not using an IDE so its not that easy to spot. thanks though - Ozzy 2012-04-03 22:17
I don't know how much an IDE would help when you don't have any errors. But still, use an IDE! Here's a free one - gilly3 2012-04-03 22:34
oh because the IDE would have colour-coded the code for me and kept it nicely indented - so I would have spotted my mistake much faster. Thanks, I already have an IDE installed but I never use it. (I'm always making small websites so I just hard-code in notepad - Ozzy 2012-04-07 13:48


try jQuery live function ..

$("div.something").live('click', function(){ 
  // do something...
2012-04-03 22:15
by Omiga
thanks for your answer. it actually works but i was overriding the innerHTML by mistake - Ozzy 2012-04-03 22:18


constructNav is not defined Try this instead:

2012-04-03 22:07
by NoName
constructNav() is defined. I changed the order though, so that links is before the scripts.js import, so that links is defined before the scripts are run - Ozzy 2012-04-03 22:14