createElement('a') with a javascript href


21st of November 2005

In Javascript, have you ever needed to create a hyperlink element like this?:

 div = document.getElementById('foo');
 newlink = document.createElement('a');
 div.appendChild(newlink);

That snippet doesn't do much. It just creates a hyperlink element with no href, class, title or content. Let's make it a bit more useful:

 newlink = document.createElement('a');
 newlink.setAttribute('class', 'signature');
 newlink.setAttribute('href', 'showSignature(xyz)');

The problem with this code is that the href becomes a link to a page called showSignature(xyz) and not a javascript function call to the function showSignature() with parameter xyz.

Solution, which took me some time to figure out, is that you have to use the javascript: prefix on the href for it to become an active javascript function caller. So this is how it should be:

 newlink = document.createElement('a');
 newlink.setAttribute('class', 'signature');
 newlink.setAttribute('href', 'javascript:showSignature(xyz)');

But I've got a sneaky feeling there's something wrong with this. Using the javascript: prefix feels a bit 1999. Can someone fill in my brainblanks on this?

UPDATE Just realised what would have been much better; set the href to # and use the onclick event instead. Problem solved.



Comment

Show all 18 comments
 
Name:
Email:
hide my email address.

Your email address will be encoded to prevent email-extraction spiders from reading it so you won't get spammed if you decide to show your email address.