I am trying to call a javascript function onclick. I have written something like this
<script type="text/javascript">
function readPage(){
alert("Hello");
}
document.getElementById('read').onclick=readPage;
</script>
<a id="read" href="">read</a>
I am trying to call readPage function but its not working?if I write onclick inside tag it works but the way I have written above is not working. why?
There is nothing wrong about how you do it, but when. You can not access the DOM
(like running getElementById())before it has loaded. The easiest thing to do is to run you code insidewindow.onloadlike this: