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");
anchor.name = "top";     // NOTE: set the anchor name.  
anchor.appendChild(document.createTextNode("Top"));

It should create the equivalent of this:

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

It works in Firefox (3.0.3), Google Chrome (0.2.149.30) 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");
anchor.id = "top";

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

Popular Posts