Updated on 6/8/2008.
It's not pretty, but the following function is a safe, bug free (to the best of my knowledge) hack for changing the name attribute as well as adding a name attribute on existing DOM elements in IE 5.5+. This function will also work with Firefox, Opera and Safari.
Below this code is a working demo.
renameEl(el, newName):
var renameEl = function (el, newName) {
el = (typeof el === "string") ? document.getElementById(el) : el;
el.name = newName;
if (/*@cc_on!@*/0) { // Internet Explorer
el.removeAttribute("name");
attributeEl = document.createElement("INPUT");
attributeEl.setAttribute("Name", newName);
holder = document.createElement("DIV");
holder.appendChild(attributeEl);
document.body.appendChild(holder);
holder.innerHTML = holder.innerHTML;
attributeEl = holder.firstChild;
el.mergeAttributes(attributeEl, false);
holder.parentNode.removeChild(holder);
}
};
Explanation: The function first removes the name attribute from the target element. It then creates a new temporary element with the desired name using a case-sensitive setAttribute 'Name' hack. The temporary element must be redrawn on the page in order for the name attribute to appear and function correctly, which is where the innerHTML comes in. In order to avoid the quirks innerHTML carries, the temporary element is isolated inside a temporary holder div. Once the temporary element has been redrawn and has successfully set a name attribute, it can be merged into the target element cleanly (thus leaving the target element alone during most of the process). Oh and for non-IE browsers just set the name attribute.
-- One of the main reasons most of the work is isolated from the rest of the page is because manipulating innerHTML removes events, and we certainly don't want that.
|
Rendered at right is a form element named 'myForm', an input text field named 'myInput', and a button without a name:
Change the Form name to 'myNewForm' Change the Text Field name to 'myNewInput' Add a name to the Button |
|
I have tested and successfully run this demo in Internet Explorer 5.5+, Firefox 2+ (although it probably works on 1.5+), Opera, and Safari.
Comments