How do I correctly loop through an array of DOM objects and assign events to them?

How do I correctly loop through an array of DOM objects and assign events to them?

Hey guys,

I have kind of a complicated setup, and I was hoping to bounce this off some one's head who's more experienced with JavaScript.

Assuming I have the following HTML markup:

  1. <div id="one-root">
  2.   ONE
  3.   <div id="one">
  4.     <ul>
  5.       <li>Testing</li>
  6.     </ul>
  7.   </div>
  8. </div>
  9. <div id="two-root">
  10.   TWO
  11.   <div id="two">
  12.     <ul>
  13.       <li>Testing</li>
  14.     </ul>
  15.   </div>
  16. </div>
  17. <div id="three-root">
  18.   THREE
  19.   <div id="three">
  20.     <ul>
  21.       <li>Testing</li>
  22.     </ul>
  23.   </div>
  24. </div>
I'm trying to set up an external JavaScript file that will assign click events to the root divs, and mouseleave events to the divs labeled "one", "two" and "three".  Now, obviously I can type it out one-by-one, rote style, but then again, that's a competitive task - isn't that what computers are for?

I tried some JavaScript like this, but it seems to always assign the final element in the array as the object upon which it does stuff.

  1. $(document).ready(function() {
  2. var nav_nodes = [
  3.     'one',
  4.     'two',
  5.     'three'
  6.   ];
  7.  
  8.   for(var obj in nav_nodes) {
  9.     var node = $('#' + nav_nodes[obj]);
  10.     var root = $('#' + nav_nodes[obj] + '-root');
  11.    
  12.     root.click(function() {
  13.       node.css("display", "block");
  14.     })
  15.    
  16.   }
  17. });
Unfortunately, what happens is that when ANY of the -root elements are clicked, the JavaScript ends up showing ONLY the final nav div (id="three"), not the one that it was "supposed" to.

I'm a little confused as to how to do this correctly.  In my way of thinking, the loop should be assigning click events to each identified DOM element (and heck, the selection is performed right inside the loop itself - I tried passing the already selected items as the elements in the array, same thing happens) and properly showing the element specified in the internal "node" variable, but it only adjusts the "display" property on the very last one shown in the array list, no matter what it is (I could reverse the order of the list and all -root nodes would set display to block for "one").

Can somebody show me what it is I'm doing wrong here?  Thank you :-)