Setting an Attr that is still attached elsewhere throws.
JavaScript
const a = document.createElement("span");
a.id = "bar";
const b = document.createElement("pre");
const id = a.attributes.getNamedItem("id");
try {
b.attributes.setNamedItem(id); // still on a
} catch (e) {
console.log(e.name); // InUseAttributeError
}
Create.document.createAttribute("type") builds a free Attr.
Assign value. Set attr.value before inserting.
Set on the map. The button now has type="button".
Tip. For simple cases, el.type = "button" or setAttribute is shorter.
Compatibility
Browser Support
NamedNodeMap.setNamedItem() is marked Baseline Widely available on MDN (since July 2015). DOM API — not a Node.js built-in.
✓ Baseline · Widely available
setNamedItem()
Insert or replace Attr nodes across modern browsers. Remove first when moving an Attr between elements.
98%Core tag support
Chrome1+
Full support
Edge12+
Full support
Firefox1+
Full support
Safari1+
Full support
Opera✓
Full support
HTML element100% supported
Bottom line: Safe for production. Use setNamedItem(attr) when working with Attr nodes; use setAttribute for simple string updates.
Frequently Asked Questions
It inserts an Attr node into the map by its name. If an attribute with the same name already exists, it is replaced. Typical use: element.attributes.setNamedItem(attr).
No. MDN marks NamedNodeMap.setNamedItem() as Baseline Widely available (since July 2015). It is not Deprecated, Experimental, or Non-standard.
The old Attr if a same-name attribute was replaced, or null if the attribute is new to the map.
InUseAttributeError (DOMException) if the Attr is still part of another map — remove it first with removeNamedItem().
setNamedItem takes an Attr node on the NamedNodeMap. element.setAttribute(name, value) takes strings and creates or updates the attribute for you.
When moving Attr nodes between elements (MDN example), or when you already have an Attr from removeNamedItem() or createAttribute(). For everyday HTML strings, setAttribute() is usually simpler.