Dynamically Adding Links (a href) using javascript and DOM

I’m adding this post strictly for the reason that every time I need to do this I spend about 20 minutes searching for an example, only to find various broken posts and incorrect answers. This way works for me every time. If you have an alternate way that works better or is less code, please feel free to post a comment.

var a = document.createElement('a');
a.setAttribute('href', 'page.html');
a.appendChild(document.createTextNode('Click Me'));

The interesting thing to note is that the text inside the link is not actually an attribute, rather it’s a a separate child node within the A element.

One Response to “Dynamically Adding Links (a href) using javascript and DOM”

  1. Ken Schultz June 18, 2010 at 4:56 pm #

    This would be the ‘only’ post I’ve ever made to one of these:

    Thank you! This actually works unlike most of the posts I’ve read.

Leave a Reply

Please leave these two fields as-is: