0

I'm so so sorry asking this very repetitive question again, yet as I searched the previous answers I could not find any solutions. In the code below, my browser returns :Uncaught TypeError: Cannot set property 'innerHTML' of undefined as I click an the generated links. Would you be kind to help me out? Thank you very much in advance.

   <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <!--generating the links--> 
<div style="background-color:gray;width:100px;min-height:200px;">
    <?php

        for ($i=0 ; $i < 9 ; $i++) { 
            echo "<a href='#' class='links'>{$i}</a><br/><br/>";    
        }

    ?>
</div>

<script type="text/javascript">

    var links = document.getElementsByTagName('a');

    for (var i=0;i<links.length;i++){
        links[i].onclick = function (){
            console.log(links[i].innerHTML);
        };
    }

</script>

</body>
</html>
Tower
  • 337
  • 1
  • 4
  • 20
  • Note that it should be `console.log(this.innerHTML);`, as you're having the classic closure issue. – adeneo Jul 25 '14 at 11:19

1 Answers1

2

In your code you are trying to access the element links[i] which's no longer exist when the onclick hander is called. To address the element within the event handler you may use this:

for (var i = 0; i < links.length; i++) {
    links[i].onclick = function() {
        console.log(this.innerHTML);
    };
}

MORE: http://www.quirksmode.org/js/this.html#link5

VisioN
  • 143,310
  • 32
  • 282
  • 281