AppendChild Link with onClick function

John picture John · Sep 19, 2012 · Viewed 11.7k times · Source

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);

Answer

Claudio Redi picture Claudio Redi · Sep 19, 2012

You have to change

link.onclick = 'loadScript()';

by

link.onclick = loadScript;

DEMO