Monday, September 29, 2008

Setting name attribute on an anchor via DOM Javascript in IE

This Javascript code creates a DOM ANCHOR element that I want to insert into my document somewhere.

var anchor = document.createElement("a"); = "top";     // NOTE: set the anchor name.  

It should create the equivalent of this:

<a name="top">Top</a>

It works in Firefox (3.0.3), Google Chrome ( and Safari (3.1.2). It doesn't work in Internet Explorer (7.0.5730.13).

Neither does this work in IE:

anchor.setAttribute("name", "top");

The only way I can get it to work in IE is by using ID instead of NAME. Either of these will work.

anchor.setAttribute("id", "top"); = "top";

Thankfully, it works in Firefox, Google Chrome and Safari too.