Attach onclick event to links programmatically

Discussion in 'Javascript' started by Miroslav Stampar [MCSD.NET / Security+], Jun 2, 2007.

  1. what am i doing wrong. i want to attach onclick event to links. i am
    using code below but it doesn't work as it should. plz help.

    <html>
    <head>
    <title>getElementById example</title>
    </head>

    <body>
    <div id="here">
    <td>
    <a href ="http://www.google.com">Google</a>
    <a href ="http://www.yahoo.com">Yahoo</a>
    </td>
    </div>

    <script>
    var elementDiv = document.getElementById('here');
    var elementsA = elementDiv.getElementsByTagName('a');

    for(var i=0;i<elementsA.length;i++)
    {
    elementsA.onclick="alert('BLA')";
    alert(elementsA.href);
    }
    </script>

    </body>
    </html>


    p.s.

    I want to do this:

    <html>
    <body>
    <a href="http://www.google.com" onclick="alert('BLA')">Google</a>
    </body>
    </html>

    THANKS IN ADVANCE :)
     
    Miroslav Stampar [MCSD.NET / Security+], Jun 2, 2007
    #1
    1. Advertising

  2. Sorry for bothering. I've found the way:

    <html>
    <head>
    <title>getElementById example</title>
    </head>

    <body>
    <div id="here">
    <td>
    <a href ="http://www.google.com">Google</a>
    <a href ="http://www.yahoo.com">Yahoo</a>
    </td>
    </div>

    <script>

    function fja()
    {
    alert("BLA");
    }

    var elementDiv = document.getElementById('here');
    var elementsA = elementDiv.getElementsByTagName('a');

    for(var i=0;i<elementsA.length;i++)
    {
    elementsA.onclick=fja;
    alert(elementsA.href);
    }

    </script>

    </body>
    </html>
     
    Miroslav Stampar [MCSD.NET / Security+], Jun 2, 2007
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Replies:
    0
    Views:
    660
  2. Warren Tang
    Replies:
    1
    Views:
    551
    Warren Tang
    Sep 17, 2008
  3. Bill
    Replies:
    1
    Views:
    338
    Ray at
    Oct 22, 2003
  4. Dark Magician
    Replies:
    1
    Views:
    145
  5. johkar
    Replies:
    22
    Views:
    293
    Lasse Reichstein Nielsen
    Jan 23, 2006
Loading...

Share This Page