AppendChild Link with onClick function

13,292

You have to change

link.onclick = 'loadScript()';

by

link.onclick = loadScript;

DEMO

Share:
13,292
John
Author by

John

Updated on June 16, 2022

Comments

  • John
    John almost 2 years

    I'm trying to use appendChild within Javascript to create a link that has a onClick attribute. I can't seem to make it work or find how to do this simple task.

    var link=document.createElement("a");
    link.appendChild(document.createTextNode("Link"));
    link.href = '#';
    link.onclick = 'loadScript()';
    document.body.appendChild(link);
    
  • zzzzBov
    zzzzBov over 11 years
    Better yet, link.addEventListener('click', loadScript, false)
  • Khadijah Celestine
    Khadijah Celestine almost 10 years
    How do I set it if loadscript has a parameter? link.onclick = loadScript(it_is_here); does not work for me.
  • Claudio Redi
    Claudio Redi almost 10 years
    @MsKhadijah : you could do link.onclick = function() { loadScript(it_is_here); }
  • Khadijah Celestine
    Khadijah Celestine almost 10 years
    Thanks. It didn't work. I cheated and used a switch statement instead.