Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can I use document.getElementById(someid).onclick for tag a

Tags:

javascript

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?

like image 386
Vipul Avatar asked Jul 28 '10 10:07

Vipul


People also ask

What is the use of document getElementById () method?

The Document method getElementById() returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly.

What can I use instead of document getElementById?

A commonly-used alternative to document. getElementById is using a jQuery selector which you read about more here.

Can I use getElementById in HTML?

The getElementById() method returns an element with a specified value. The getElementById() method returns null if the element does not exist. The getElementById() method is one of the most common methods in the HTML DOM. It is used almost every time you want to read or edit an HTML element.


2 Answers

It will work with an empty href attribute (then the current URL of the page will be used), but you have to use, as already mentioned, window.onload to attach the click handler, or you have to move the script block after the a element.

Otherwise getElementById cannot find the element because it does not yet exist in the DOM tree.

<a id="read" href="">read</a> 

<script type="text/javascript">
    function readPage(){
        alert("Hello");
        return false;
    }

    document.getElementById('read').onclick=readPage;
</script>

​ As already mentioned, you use e.g. return false; to make the browser not follow the URL. You even need this if you change the URL to href="#" because otherwise the browser will scroll the page to the top.

Test it yourself: http://jsfiddle.net/Nj4Dh/1/


Read more about the traditional event registration model.

like image 180
Felix Kling Avatar answered Nov 15 '22 13:11

Felix Kling


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 inside window.onload like this:

window.onload = function () {
   document.getElementById("read").onclick=readPage;
};
like image 40
Bjarne Mogstad Avatar answered Nov 15 '22 15:11

Bjarne Mogstad