I want to learn pure JS, I ran into a problem, it does not work:

(function () { document.getElementById('login').onclick = function () { alert(123); return false; }; })(); <a href="#" id="login">Войти</a> 

You can do without simply inserting the onclick attribute into the tag, but it is interesting to do it using this method, but for some reason it does not work.

  • one
    Now someone will explain to you why this is not working, and you simply place the script after the html you are working with - Specter
  • Yeah, thanks, it works. - rimlin
  • Attention! Code of the form (function () {...}) (); it is executed immediately after the download and does not even wait for the loading of the code that follows after. Do not forget about it. - istem

2 answers 2

Perhaps this will help you:

 <script type="text/javascript"> window.onload = function(){ document.getElementsByTagName('p')[0].onclick = function(){ location.replace("http://www.ya.ru"); }; }; </script> <p>click</p> 

Only it is necessary to redo everything for the link.

    <a href="#" id="login"> Login </a>

     (function () { document.getElementById('login').onclick = function () { return function() { alert(123); }; }; })();