JavaScript Element setAttributeNode() Method

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

What You’ll Learn

Element.setAttributeNode() is an instance method that adds an Attr node to an element. Learn MDN’s clone- lang example, document.createAttribute(), the replaced-node return value, when to prefer setAttribute(), and five try-it labs aligned with MDN.

01

Kind

Instance method

02

Arg

Attr node

03

Returns

Replaced Attr

04

Clone

cloneNode(true)

05

vs setAttribute

node vs string

06

Status

Baseline widely

Introduction

Day-to-day code usually writes attributes with element.setAttribute("lang", "en-US"). setAttributeNode() works at the Attr node level: you pass an actual Attr object instead of a name/value pair.

MDN recommends this API when you already have (or need to build) an attribute node—for example cloning lang from one element onto another. If you only need to set a string value, prefer setAttribute().

💡
Beginner tip

An Attr can belong to only one element. To copy an attribute, clone it first: attr.cloneNode(true), then call target.setAttributeNode(clone) (MDN).

This page is part of JavaScript Element. Pair with getAttributeNode(), setAttribute(), and removeAttributeNode().

Understanding the setAttributeNode() Method

Calling el.setAttributeNode(attr) attaches the given Attr to el. If an attribute with the same name already exists, that attribute is replaced and the old node is returned (MDN).

  • It is an instance method on Element.
  • Takes one parameter: an Attr node to add (MDN).
  • Returns the replaced Attr node, if any (MDN).
  • Prefer setAttribute() when you do not need to work with Attr nodes (MDN).
  • Clone before reusing an Attr from another element.
  • Pairs with getAttributeNode() and removeAttributeNode().

📝 Syntax

General form of Element.setAttributeNode (MDN):

JavaScript
setAttributeNode(attribute)

Parameters

ParameterTypeDescription
attributeAttrThe Attr node to add to the element (MDN).

Return value

TypeDescription
Attr or emptyThe replaced attribute node, if any (MDN).

Notes

MDN: if the named attribute already exists on the element, that attribute is replaced with the new one and the replaced one is returned.

Common patterns

JavaScript
// MDN — clone lang from one element to another
const d1 = document.getElementById("one");
const d2 = document.getElementById("two");
const a = d1.getAttributeNode("lang");
d2.setAttributeNode(a.cloneNode(true));

// Create a new Attr from scratch
const attr = document.createAttribute("data-role");
attr.value = "admin";
el.setAttributeNode(attr);

// Capture the replaced node (if any)
const old = el.setAttributeNode(document.createAttribute("title"));
// old is the previous title Attr, or empty if none existed

⚡ Quick Reference

GoalCode
Add an Attr nodeel.setAttributeNode(attr)
Clone Attr to another elementt.setAttributeNode(a.cloneNode(true))
Create Attr then setdocument.createAttribute("id")
Simple name/value writeel.setAttribute("id", "x")
Get Attr firstel.getAttributeNode("lang")
MDN statusBaseline Widely available (since July 2015)

🔍 At a Glance

Four facts to remember about Element.setAttributeNode().

Arg
Attr

Attribute node

Returns
old Attr?

If replaced

Baseline
widely

Since July 2015

Prefer
setAttribute

For simple cases

📋 setAttributeNode() vs setAttribute()

setAttributeNode(attr)setAttribute(name, value)getAttributeNode(name)
InputAn Attr objectName + string valueAttribute name string
ReturnsReplaced Attr (if any)undefinedAttr or null
Best forCloning / Attr workflowsEveryday attribute writesReading Attr details
MDN guidanceWhen you need the nodePreferred for simple setsWhen you need Attr props
Clone needed?Yes, to copy between elementsNoN/A (read-only)

Examples Gallery

Examples follow MDN Element.setAttributeNode() patterns. Use View Output or Try It Yourself for each case.

📚 Getting Started

MDN’s core demo—copy lang and create a new Attr.

Example 1 — Clone lang Between Elements (MDN)

Copy the lang attribute from one div to another using cloneNode.

JavaScript
// HTML: <div id="one" lang="en-US">one</div>
//       <div id="two">two</div>
const d1 = document.getElementById("one");
const d2 = document.getElementById("two");
const a = d1.getAttributeNode("lang");

d2.setAttributeNode(a.cloneNode(true));

console.log(d2.getAttribute("lang")); // "en-US"
Try It Yourself

How It Works

getAttributeNode("lang") returns the Attr. cloneNode(true) makes a copy so both elements can have their own Attr. Then setAttributeNode attaches the clone to d2 (MDN).

Example 2 — Create Attr with createAttribute

Build a new attribute node from scratch and attach it.

JavaScript
const el = document.getElementById("box");
const attr = document.createAttribute("data-role");
attr.value = "admin";

el.setAttributeNode(attr);

console.log(el.getAttribute("data-role")); // "admin"
console.log(attr.ownerElement.id);         // "box"
Try It Yourself

How It Works

After setAttributeNode, attr.ownerElement points at the element that owns the attribute.

📈 Practical Patterns

Replacing attributes, copying titles, and choosing the right API.

Example 3 — Replaced Attr Is Returned (MDN)

When the name already exists, the old Attr comes back from the call.

JavaScript
const el = document.getElementById("item");
// <div id="item" title="old">

const next = document.createAttribute("title");
next.value = "new";

const replaced = el.setAttributeNode(next);

console.log(replaced.value);           // "old"
console.log(el.getAttribute("title")); // "new"
Try It Yourself

How It Works

MDN: the existing attribute is replaced and the replaced node is returned. Useful when you want to keep the old Attr for later.

Example 4 — Copy title With Clone

Share a tooltip attribute across related UI elements.

JavaScript
const source = document.getElementById("source");
const target = document.getElementById("target");
const titleAttr = source.getAttributeNode("title");

target.setAttributeNode(titleAttr.cloneNode(true));

console.log(target.getAttribute("title"));
// "Save document"
Try It Yourself

How It Works

Same pattern as MDN’s lang example: get the Attr, clone it, then set it on the destination element.

Example 5 — Prefer setAttribute() for Simple Writes

MDN: use setAttribute() when you do not need to work with Attr nodes.

JavaScript
const el = document.getElementById("btn");

// Everyday write — preferred for simple cases (MDN)
el.setAttribute("aria-label", "Close");

// Equivalent Attr workflow (more steps)
const attr = document.createAttribute("aria-label");
attr.value = "Close";
el.setAttributeNode(attr);

console.log(el.getAttribute("aria-label")); // "Close"
Try It Yourself

How It Works

Both approaches set the same attribute. Reach for setAttributeNode() when you already have an Attr (clone, inspect, or replace workflows).

🚀 Common Use Cases

  • Cloning attributes such as lang or title between elements (MDN).
  • Building Attr nodes with document.createAttribute() before attaching them.
  • Capturing the previous Attr when replacing an attribute of the same name.
  • Working with attribute nodes returned by getAttributeNode().
  • Teaching the difference between string APIs and Attr-node APIs.
  • Pairing with removeAttributeNode() for full Attr lifecycle control.

🧠 How setAttributeNode() Attaches Attr Nodes

1

Obtain an Attr

Create one with createAttribute, or get/clone one with getAttributeNode.

Attr
2

Call setAttributeNode

el.setAttributeNode(attr) adds the node to the element (MDN).

Attach
3

Replace if same name

If that attribute already exists, the old Attr is replaced and returned (MDN).

Replace
4

Markup updated

Verify with getAttribute() or attr.ownerElement.

📝 Notes

  • Not Deprecated, Experimental, or Non-standard on MDN (Baseline Widely available, July 2015).
  • Prefer setAttribute() when you do not need Attr-node workflows (MDN).
  • Clone Attr nodes before attaching them to another element.
  • Same-name attributes are replaced; the old Attr is returned (MDN).
  • For namespaced Attr nodes, use setAttributeNodeNS() (MDN).
  • Related: getAttributeNode(), setAttribute(), removeAttributeNode(), JavaScript hub.

Browser Support

Element.setAttributeNode() is Baseline Widely available (MDN: across browsers since July 2015). Logos use the shared browser-image-sprite.png sprite from this project.

Baseline Widely available

Element.setAttributeNode()

Add or replace Attr nodes on an element — the Attr-level companion to setAttribute().

Baseline Widely available
Google Chrome Supported · Desktop & Mobile
Yes
Microsoft Edge Supported · Chromium
Yes
Mozilla Firefox Supported · Desktop & Mobile
Yes
Apple Safari Supported · macOS & iOS
Yes
Opera Supported · Modern versions
Yes
Internet Explorer Supported in legacy IE
Yes
setAttributeNode() Excellent

Bottom line: Use setAttributeNode() when you work with Attr objects (clone, createAttribute, capture replaced nodes). Prefer setAttribute() for everyday name/value writes.

Conclusion

Element.setAttributeNode() attaches an Attr node to an element and returns any replaced Attr. It shines for clone and Attr-object workflows; for simple string sets, use setAttribute().

Continue with getAttributeNode(), removeAttributeNode(), shadowRoot, or the JavaScript hub.

💡 Best Practices

✅ Do

  • Clone Attrs with cloneNode(true) when copying (MDN)
  • Use setAttribute() for simple name/value writes (MDN)
  • Capture the return value when replacing an existing Attr
  • Pair with getAttributeNode() for read/write Attr flows
  • Set attr.value before attaching a new Attr

❌ Don’t

  • Reuse the same Attr on two elements without cloning
  • Prefer Attr APIs when a string set is enough
  • Forget that same-name attrs replace the old node
  • Confuse with setAttributeNS / setAttributeNodeNS
  • Ignore ownerElement when debugging Attr ownership

Key Takeaways

Knowledge Unlocked

Five things to remember about Element.setAttributeNode()

Attach Attr nodes — clone when copying.

5
Core concepts
📄 02

Returns

replaced Attr

Value
📋 03

Clone

cloneNode(true)

Copy
04

Baseline

widely available

Status
05

Prefer

setAttribute

Simple

❓ Frequently Asked Questions

It adds an Attr node to the element. If an attribute with the same name already exists, that attribute is replaced and the old Attr is returned (MDN).
No. MDN marks Element.setAttributeNode() as Baseline Widely available (across browsers since July 2015). It is not Deprecated, Experimental, or Non-standard.
The replaced Attr node if one existed with the same name; otherwise typically null/undefined for a new attribute (MDN: the replaced attribute node, if any).
MDN: use setAttributeNode() when you need to work with the Attr node first (for example cloning from another element). Prefer setAttribute() for simple name/value writes.
An Attr can belong to only one element. Clone it with attr.cloneNode(true) before calling setAttributeNode on the target (MDN example).
Use document.createAttribute(name), set attr.value, then element.setAttributeNode(attr).
Did you know?

MDN’s classic demo clones lang from one element to another with getAttributeNode + cloneNode(true) + setAttributeNode—the same pattern works for any attribute you need to copy.

Next: setAttributeNodeNS()

Continue with namespaced Attr-node workflows.

setAttributeNodeNS() →

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.

8 people found this page helpful