JavaScript NamedNodeMap setNamedItem() Method

Beginner
⏱️ 11 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Baseline Widely available
Instance method

What You’ll Learn

The setNamedItem() method of a NamedNodeMap inserts or replaces an Attr node by name. Learn the MDN move-class example, what the return value means, the InUseAttributeError when an Attr is still attached elsewhere, and how it compares with setAttributeNode()—with five examples and try-it labs.

01

Kind

Instance method

02

Returns

Old Attr|null

03

Arg

Attr node

04

Replace

same name

05

Use case

Move attrs

06

Status

Baseline widely

Introduction

getNamedItem() reads attributes; removeNamedItem() deletes them. setNamedItem() is how you add or update an Attr on element.attributes.

MDN’s classic demo removes class from a <span> and moves it onto a <pre> with pre.attributes.setNamedItem(classAttribute)—then shows what happens when you try to set an Attr that is still on another element.

💡
Beginner tip

For most HTML tasks, element.setAttribute("class", "foo") is enough. Use setNamedItem when you already have an Attr node—especially after removeNamedItem() detached it from its old owner.

Understanding the setNamedItem() Method

An instance method on NamedNodeMap that puts an Attr into the map, keyed by its name.

  • attr — the Attr node to insert (from createAttribute, removeNamedItem, etc.).
  • Returns — the replaced Attr if a same-name attribute existed, or null if the name is new.
  • Replace rule — same name in the map → old Attr is replaced.
  • Exception — thrown if the Attr is still part of another map (MDN).
  • Common sourceelement.attributes.setNamedItem(attr).
  • Baseline Widely available on MDN (since July 2015).

📝 Syntax

Call the method on a NamedNodeMap (usually from element.attributes):

JavaScript
namedNodeMap.setNamedItem(attr)

Parameters

  • attr — an Attr node to add or replace in the map.

Return value

The old Attr if replaced, or null when the name is new.

Exceptions

Thrown if the attribute is still part of another map (e.g. still on a different element).

Typical pattern (MDN idea)

JavaScript
const span = document.querySelector("span");
const pre = document.querySelector("pre");

const classAttribute = span.attributes.removeNamedItem("class");
pre.attributes.setNamedItem(classAttribute);

console.log(pre.className); // "foo" — class moved from span to pre

⚡ Quick Reference

GoalCode / note
Add/replace Attrel.attributes.setNamedItem(attr)
Move attributeremoveNamedItem then setNamedItem
New nameReturns null
Same name existsReturns old Attr
Still on other elementThrows (MDN)
MDN statusBaseline Widely available (since July 2015)

🔍 At a Glance

Four facts to remember about NamedNodeMap.setNamedItem().

Returns
Attr|null

Old or new

Arg
Attr

Node object

In use
throws

Other map

Baseline
widely

Since Jul 2015

Examples Gallery

Examples follow MDN NamedNodeMap.setNamedItem. Labs use live element.attributes on real DOM nodes.

📚 Getting Started

MDN pattern: move an attribute between elements.

Example 1 — MDN Move class from <span> to <pre>

Remove from one map, set on another—attribute travels with the Attr node.

JavaScript
const span = document.querySelector("span");
const pre = document.querySelector("pre");

let result = `The <pre> element initially contains ${pre.attributes.length} attributes.\n\n`;
result += "We remove `class` from <span> and add it to <pre>.\n";

const classAttribute = span.attributes.removeNamedItem("class");
pre.attributes.setNamedItem(classAttribute);

result += `The <pre> element now contains ${pre.attributes.length} attributes.`;
console.log(result);
Try It Yourself

How It Works

MDN: removeNamedItem detaches the Attr; setNamedItem attaches it to the new element.

Example 2 — Replace Existing Attribute (Returns Old Attr)

Setting a same-name Attr returns the previous one.

JavaScript
const box = document.querySelector("#demo");
const map = box.attributes;

const newClass = document.createAttribute("class");
newClass.value = "updated";

const old = map.setNamedItem(newClass);

console.log(old?.value, box.className);
Try It Yourself

How It Works

MDN: if the name already exists, the old Attr is returned and replaced.

📈 Edge Cases & Comparisons

New names, in-use errors, and element-level alternatives.

Example 3 — New Attribute Returns null

Adding a brand-new name gives no replaced node back.

JavaScript
const box = document.querySelector("#demo");
const role = document.createAttribute("data-role");
role.value = "panel";

const replaced = box.attributes.setNamedItem(role);

console.log(replaced === null, box.getAttribute("data-role"));
Try It Yourself

How It Works

MDN: return null when the attribute name is new to the map.

Example 4 — InUseAttributeError When Attr Is Still Attached

MDN: cannot set an Attr that still belongs to another element’s map.

JavaScript
const span = document.querySelector("span");
const pre = document.querySelector("pre");

const id = span.attributes.getNamedItem("id");

try {
  pre.attributes.setNamedItem(id);
} catch (error) {
  console.log(error.name);
}
Try It Yourself

How It Works

Remove the Attr first with removeNamedItem, then call setNamedItem on the target.

Example 5 — setNamedItem() vs setAttributeNode()

Map-level and element-level APIs share the same return semantics.

JavaScript
const a = document.querySelector("#box-a");
const b = document.querySelector("#box-b");

const attr = document.createAttribute("title");
attr.value = "Hello";

const viaMap = a.attributes.setNamedItem(attr);
const viaElement = b.setAttributeNode(document.createAttribute("title"));

console.log(viaMap === null, typeof viaElement);
Try It Yourself

How It Works

Both accept an Attr and return the replaced node or null—setAttributeNode is the element shortcut.

🚀 Common Use Cases

  • Move attributes between elements (MDN class demo).
  • Insert Attr nodes created with document.createAttribute().
  • Replace an existing attribute while keeping the old Attr reference.
  • Teach low-level DOM attribute mutation vs string APIs.
  • Interop with legacy code that works on NamedNodeMap directly.

🔧 How It Works

1

Get or create Attr

From createAttribute, or detached via removeNamedItem (MDN move pattern).

Input
2

Call setNamedItem(attr)

Attr must not still belong to another element's map—or MDN throws.

Insert
3

Return old or null

Same name replaced → old Attr returned. New name → null.

Result
4

Element updated

getNamedItem(attr.name) returns the new Attr; element reflects the change.

📝 Notes

  • MDN: Baseline Widely available (since July 2015) — no Deprecated / Experimental / Non-standard banner.
  • Attr must be detached before moving—use removeNamedItem first.
  • Same name → replace and return old Attr; new name → return null.
  • Prefer setAttribute() for simple string updates on HTML.
  • Related learning: removeNamedItem(), setAttributeNode(), getNamedItem(), Element.attributes.

Universal Browser Support

NamedNodeMap.setNamedItem() is marked Baseline Widely available on MDN (since July 2015). Logos use the shared browser-image-sprite.png sprite from this project.

Baseline · Widely available

NamedNodeMap.setNamedItem()

Inserts or replaces an Attr by name—returns the old Attr or null, throws if the Attr is still in another map.

Universal Widely available
Google Chrome Full support · Desktop & Mobile
Full support
Mozilla Firefox Full support · Desktop & Mobile
Full support
Apple Safari Full support · macOS & iOS
Full support
Microsoft Edge Full support · Chromium
Full support
Opera Full support · Modern versions
Full support
Internet Explorer Supported on NamedNodeMap (legacy DOM)
Legacy OK
NamedNodeMap.setNamedItem() Excellent

Bottom line: Call map.setNamedItem(attr) on element.attributes to add or replace attributes with Attr nodes.

Conclusion

NamedNodeMap.setNamedItem() inserts or replaces an Attr by name, returning the old node or null. Use it to move attributes between elements (MDN), detach with removeNamedItem first, and prefer setAttribute() for everyday HTML.

Continue with setNamedItemNS(), removeNamedItem(), setAttributeNode(), or the JavaScript hub.

💡 Best Practices

✅ Do

  • Detach with removeNamedItem before moving Attr nodes
  • Use createAttribute for brand-new free Attr objects
  • Check the return value to see if you replaced an old Attr
  • Use setAttribute for simple name/value updates
  • Wrap setNamedItem in try/catch when reuse is uncertain

❌ Don’t

  • Set an Attr still attached to another element (MDN throws)
  • Assume it always returns null
  • Use setNamedItem when strings suffice
  • Forget that same-name attrs are silently replaced
  • Move attrs without updating your mental model of owner elements

Key Takeaways

Knowledge Unlocked

Five things to remember about setNamedItem()

Insert or replace Attr nodes by name.

5
Core concepts
⚙️02

Arg

Attr

Params
⚠️03

In use

throws

MDN
📄04

Move

remove then set

Pattern
🎯05

Baseline

since Jul 2015

Status

❓ 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. On elements, element.attributes.setNamedItem(attr) adds or updates that attribute on the element.
No. MDN marks NamedNodeMap.setNamedItem() as Baseline Widely available (since July 2015). It is not Deprecated, Experimental, or Non-standard.
The old Attr node if an attribute with the same name was replaced, or null if the attribute is new to the map.
MDN documents an exception when the Attr is still part of another map—typically InUseAttributeError if you try to set an attribute that is still attached to a different element.
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 object from removeNamedItem() or createAttribute(). For everyday HTML, setAttribute() is usually simpler.
Did you know?

MDN’s setNamedItem() demo moves class from <span> to <pre> with removeNamedItem + setNamedItem, then shows InUseAttributeError when trying to set id while it is still on the span.

Explore setNamedItemNS()

MDN alias for inserting namespaced Attr nodes.

setNamedItemNS() method →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful