Mobile version of this pageMajor performance fix on file searches
Next:
Mvbackupfiles - a script to "delete" back autosaved backup files
Related blogs
IssueTrackerProduct feature listDOM Scripting
setAttribute('style', ...) workaround for IE
Add links to a text with URLs
firstChild.nodeValue vs. innerHTML
Related by category
createElement('a') with a javascript href
createelement, hyperlink, getelementbyid, appendchild, sneaky, signature
21st of November 2005
In Javascript, have you ever needed to create a hyperlink element like this?:
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.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.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
You should never set an href to # for a javascrpit event. You were right to set an onclick event, but the href should really be javascript:void(0) to avoid refresh issues.
Apparently it works but because we cannot set 'Text' property/attribute of <a> tag we cannot see the generated hyperlinks. That would be great if someone can let me know how to set it.
try new.innerHTML = 'link_text' to get the text in there
thank you very much, but i have a question, what about de text you are going to click?
tn = document.createTextNode('link text');
newlink.appendChild(tn);
That will create the clickable text.







Save this page in del.icio.us
FYI: I am writting a JSP that also dynamically creates an <a href> element and found that the href="#" did not work, but the href="javascript:function" did work. Thanks for the help.