IE tries to be helpful when using JavaScript to set the href attribute

When using JavaScript to set the href attribute of an anchor tag, IE sometimes updates the inner HTML. Why does this happen and what are some solutions?

Posted by Curtis Miller on June 17, 2010

Have you ever tried to set an anchor tag's href attribute using JavaScript? It's pretty easy, even without a JavaScript library (jQuery, Prototype, etc.). All you need to do is find (or create) the element and then set the href attribute to the desired text.

Now, try executing the following in IE:

What would you expect to be the value of link.innerHTML? Turns out that it is the same as the href value, 'http://flatterline.com'. It seems that, on IE only, if the inner HTML of an anchor tag looks like a URL, then upon replacing the href, it will also replace the inner HTML. Try the same experiment, but with link text that does not look like a URL:

Inspecting the innerHTML value will show that it was not replaced.

This is a browser level quirk, so using a JavaScript library won't save from this unless your library has specifically made a special case for this. I originally saw this when using jQuery and thought it might be a problem with the jQuery framework.

I think the best workaround here is that when modifying an anchor tag with JavaScript, set attributes first, then set the link text.

What do you think? Have a different workaround or solution?

Need web application development, maintenance for your existing app, or a third party code review?

Velocity Labs can help.

Hire us!