javascript events with loops
<blockquote>
  <p><strong>Possible Duplicate:</strong><br>
  <a href="http://stackoverflow.com/questions/7004619/javascript-only-sets-attribute-for-last-item-in-array">Javascript only sets attribute for last item in array</a>  </p>
</blockquote>



<p>I've just dived into some basic javascript+dom learning, and can't quite understand only the last element is being toggled? I'm at a lost as to why attaching an event to an element, seems to overwrite the previous ones as well. </p>

<p><strong>JavaScript:</strong></p>

<pre><code>window.onload = function() {
    // Simple log
    var c = function(x) {
        return console.log(x);
    };

    var hasClass = function(ele, cls) {
        return ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
    };

    var toggleClass = function(ele, cls) {
        if (!hasClass(ele, cls)) {
            ele.className += " " + cls;


        } else {
            var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
            ele.className = ele.className.replace(reg, '');
        }
    };

    var toggle = function(clk) {
        c(clk);
    }

    var el = document.getElementsByClassName('time');
    for (i = 0; i &lt; el.length; i++) {
        var btnToggle = el[i].getElementsByClassName('btn-toggle')[0];
        var clk = el[i].getElementsByClassName('clock')[0];
        btnToggle.addEventListener('click', function() {
            toggle(clk)
        }, false);
    }
};​
</code></pre>

<p><strong>HTML:</strong> </p>

<pre><code>&lt;section&gt;
    &lt;div class="time"&gt;
        &lt;a href="#" class="btn-toggle"&gt;Show the time&lt;/a&gt;
        &lt;div class="clock"&gt;Clock1&lt;/div&gt;
    &lt;/div&gt;

    &lt;div class="time"&gt;
        &lt;a href="#" class="btn-toggle"&gt;Show the time&lt;/a&gt;
        &lt;div class="clock"&gt;Clock2&lt;/div&gt;
    &lt;/div&gt;

    &lt;div class="time"&gt;
        &lt;a href="#" class="btn-toggle"&gt;Show the time&lt;/a&gt;
        &lt;div class="clock"&gt;Clock3&lt;/div&gt;
    &lt;/div&gt;

&lt;/section&gt;
</code></pre>

<p>Thanks for your sage advice!</p>
