Javascript keeps returning undefined when trying to access divs through DOM

Magentix

if (OP.statement == false) postCount++;
Reaction score
107
Ok, after hours of trying to fix this, I just can't seem to get this to work...

The problem lies in the nav_setPops function where I try to set the onmouseover and onmouseout of every div that has the class "nav_link".

I do not wish to use inline onmouseover and onmouseout to keep my HTML clean (even though I tested it that way and it worked that way).

Methods I've tried to access the divs in question:
Code:
var nav_links = document.getElementById('nav').childNodes;
var nav_links = document.getElementById('nav').getElementsByTagName('div');
...

I can access single divs by specifically typing in their id in a document.getElementById, but all other means (byTagName, childNodes, etc..) fail..

Anyone able to help?
I've cleaned up the code so the only remaining part is what is causing this error.

Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
	<head>
		<script type="text/javascript">			
			function nav_setPops()
			{
				var nav_links = document.getElementById('nav').childNodes;
				
				for (link in nav_links)
				{
					// test to see if I accessed the div, but it returns undefined
					alert(link.innerHTML);
					
					if (link.className == 'nav_link')
					{
						link.onmouseover = new Function("a_function()");
						link.onmouseout = new Function("b_function();");
					}
				}
			}
		</script>
	</head>

	<body>
		<div id="nav">
			<div class="nav_link" id="nav_link_0"><a href="">Home</a></div>
			<div class="nav_link" id="nav_link_12"><a href="?page=12">Resources</a></div>
			<div class="nav_link" id="nav_link_7"><a href="?page=7">Varia</a></div>
		</div>
		
		<script type="text/javascript">nav_setPops();</script>
	</body>
</html>
 

Magentix

if (OP.statement == false) postCount++;
Reaction score
107
If anyone wishes to know the answer:

Fails:
Code:
for(nav in nav_links)

Works:
Code:
for(i=0;i<nav_links.length;i++)
 

Xienoph

You can change this now in User CP.
Reaction score
43
That's because if you do the first one, nav will be set to the array indexes. So you need to do:

Code:
for (i in nav_links)
    var nav = nav_links[i];
 
General chit-chat
Help Users
  • No one is chatting at the moment.

      The Helper Discord

      Members online

      Affiliates

      Hive Workshop NUON Dome World Editor Tutorials

      Network Sponsors

      Apex Steel Pipe - Buys and sells Steel Pipe.
      Top