Set div’s all anchor tags onclick event using javascript

Here is an example to set all child anchor tags onclick event.
A div (id str1) has 3 anchor tags (First, Second and Third). When user clicks on any link, it should call “ShowValue” javascript method which displays text of that link. We have to set onclick event dynamically using javascript. See following for this:

<script type="text/javascript" >
function SetThis(anc)
{    
var s = document.getElementById(anc).getElementsByTagName("a");   
for (var i=0;i<s.length;i++)
{
s[i].onclick = Function("ShowValue('"+s[i].innerText+"')");     
}          
}
function ShowValue(atag)
{   
alert(atag); 
}     
</script>
<div id= "str1">
<a href="javascript: void(0)">First</a><br/>
<a href="javascript: void(0)">Second</a><br/>
<a href="javascript: void(0)">Third</a><br/>
</div>
<script type="text/javascript">
SetThis('str1'); 
</script>

In the code I used
s[i].onclick = Function("ShowValue('"+s[i].innerText+"')");

Suppose If I use
s[i].onclick = ShowValue(s[i].innerText);
It is executed immediately and on page load, ‘First’ is displayed. But onclick, “Object expected” error is thrown.
If I use
s[i].onclick =function(){ ShowValue(s[i].innerText)};
In this case, We get error:
“’s[…].innerText’ is null or not an object”
So s[i].onclick = Function("ShowValue('"+s[i].innerText+"')"); works perfect.
Hope, It helps.

1 comment:

  1. I think in this case :

    s[i].onclick =function(){ ShowValue(this.innerText)};

    will do ... :)

    ReplyDelete