IE tries to be helpful when using JavaScript to set the href attribute
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?
Note that this also happens for an existing a element for which you just want to edit the href attribute. For instance:
var loc = //any a element in the document
loc.href = "mailto:info@example.com";
The result is that "mailto:info@example.com" replaces both the href attribute and child nodes of the a element.
Why would IE do this? Obviously, it's a bug, but a voluntary one, even: they must have extra code specially to change the "innerHTML" beside the href attribute.
December 21st, 2010 at 1:56 am