Attach onclick event to links programmatically

  • Thread starter Miroslav Stampar [MCSD.NET / Security+]
  • Start date
M

Miroslav Stampar [MCSD.NET / Security+]

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 :)
 
M

Miroslav Stampar [MCSD.NET / Security+]

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>
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,825
Latest member
VernonQuy6

Latest Threads

Top