JavaScript Document createAttribute() Method

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

What You’ll Learn

document.createAttribute() is an instance method that creates a new Attr node (see MDN Document: createAttribute()). Learn how to set attr.value, attach it with setAttributeNode(), the lowercase localName rule, how it compares to setAttribute(), and five try-it labs.

01

Kind

Instance method

02

Arg

localName

03

Returns

Attr node

04

Attach

setAttributeNode

05

Name rule

lowercase

06

Status

Baseline

Introduction

Most beginners set attributes with a one-liner: element.setAttribute("class", "active"). That is usually the best choice.

Sometimes you need an actual attribute node — an Attr object you can inspect, pass around, or attach with setAttributeNode(). That is when you call document.createAttribute(localName).

💡
Three-step pattern (MDN)

1) const attr = document.createAttribute("my_attrib")
2) attr.value = "newVal"
3) element.setAttributeNode(attr)

MDN notes the DOM does not enforce which attributes belong on which elements when you create them this way — you are responsible for valid HTML.

Related tutorials: setAttribute(), getAttribute(), attributes.

Understanding document.createAttribute()

An instance method on the page’s document object. Part of the DOM Core API (MDN).

  • ParameterlocalName: attribute name string (MDN).
  • Return value — an Attr node (MDN).
  • Name casinglocalName is converted to lowercase (MDN).
  • Value — assign attr.value before attaching.
  • Attachelement.setAttributeNode(attr) adds it to an element.
  • Validation — invalid names throw; DOM does not validate element pairing (MDN).

📝 Syntax

General form of Document.createAttribute (MDN):

JavaScript
createAttribute(localName)

Parameters

  • localName — string for the attribute name; initializes localName on the new Attr (MDN).

Return value

An Attr node (MDN).

MDN basic example

JavaScript
const node = document.getElementById("div1");
const a = document.createAttribute("my_attrib");
a.value = "newVal";
node.setAttributeNode(a);
console.log(node.getAttribute("my_attrib")); // "newVal"

Everyday alternative

JavaScript
// Simpler for most apps:
node.setAttribute("my_attrib", "newVal");

⚡ Quick Reference

GoalCode
Create Attrdocument.createAttribute("data-id")
Set valueattr.value = "42"
Attachel.setAttributeNode(attr)
Read backel.getAttribute("data-id")
Attr nameattr.name (lowercase)
MDN statusBaseline Widely available

🔍 At a Glance

Four facts about document.createAttribute().

Returns
Attr

node

Name
lowercase

MDN

Attach
setAttributeNode

on element

Prefer
setAttribute

usually

📋 Attr node workflow vs string attributes

StepcreateAttribute pathsetAttribute path
1. Define namecreateAttribute("role")setAttribute("role", ...)
2. Set valueattr.value = "button"Second argument
3. Applyel.setAttributeNode(attr)Done in one call
Object typeAttr nodeString on element

Examples Gallery

Examples follow MDN Document: createAttribute() and show practical Attr-node patterns.

📚 Getting Started

Create an Attr node and attach it to an element.

Example 1 — MDN basic: create, set value, attach

The official three-step pattern from MDN.

JavaScript
const node = document.getElementById("div1");
const a = document.createAttribute("my_attrib");
a.value = "newVal";
node.setAttributeNode(a);

console.log(node.getAttribute("my_attrib")); // "newVal"
Try It Yourself

How It Works

createAttribute builds a detached Attr; setAttributeNode links it to the element.

Example 2 — localName becomes lowercase (MDN)

Pass mixed case; the created node name is lowercased.

JavaScript
const attr = document.createAttribute("My_Custom_Attr");

console.log(attr.name);       // "my_custom_attr"
console.log(attr.localName);  // "my_custom_attr"
Try It Yourself

How It Works

MDN: the string given in the parameter is converted to lowercase.

📈 Practical Patterns

Data attributes, comparisons, and Attr inspection.

Example 3 — Custom data-* attribute

Build a data attribute node for a list item.

JavaScript
const li = document.createElement("li");
li.textContent = "Task";

const dataStatus = document.createAttribute("data-status");
dataStatus.value = "done";
li.setAttributeNode(dataStatus);

console.log(li.dataset.status); // "done"
Try It Yourself

How It Works

Once attached, the attribute behaves like any other — readable via dataset or getAttribute.

Example 4 — Same result with setAttribute()

Compare the Attr-node path with the simpler string API.

JavaScript
const el = document.createElement("div");

// Attr node path
const attr = document.createAttribute("title");
attr.value = "Tooltip";
el.setAttributeNode(attr);

// Equivalent one-liner:
// el.setAttribute("title", "Tooltip");

console.log(el.getAttribute("title")); // "Tooltip"
console.log(el.getAttributeNode("title") instanceof Attr); // true
Try It Yourself

How It Works

After attachment, getAttributeNode returns the live Attr on the element.

Example 5 — Inspect Attr properties

Read name, value, and ownerElement after attach.

JavaScript
const button = document.createElement("button");
button.textContent = "Save";

const disabledAttr = document.createAttribute("disabled");
disabledAttr.value = "";
button.setAttributeNode(disabledAttr);

console.log({
  name: disabledAttr.name,
  value: disabledAttr.value,
  ownerTag: disabledAttr.ownerElement?.tagName,
  specified: disabledAttr.specified
});
Try It Yourself

How It Works

ownerElement points to the element that owns the attribute after setAttributeNode.

🚀 Common Use Cases

  • Attribute node APIs — when code expects an Attr object, not just strings.
  • setAttributeNode workflows — move or replace attribute nodes between elements.
  • DOM teaching — show that attributes are nodes, not only strings.
  • Legacy DOM scripts — maintain code that creates attributes before attaching.
  • Not for everyday UI — prefer setAttribute() for simple updates.
  • Namespaced markup — use createAttributeNS() for SVG/XML namespaces.

🧠 How createAttribute() Works

1

Pass localName

MDN: a string for the attribute name; converted to lowercase.

Input
2

Get detached Attr

Browser returns a new attribute node not yet on any element.

Create
3

Set attr.value

Assign the attribute value before attaching to an element.

Value
4

setAttributeNode(attr)

Attach the Attr to an element; read with getAttribute.

📝 Notes

  • MDN: Baseline Widely available since July 2015.
  • localName is lowercased (MDN).
  • Invalid names throw — no whitespace, NULL, /, =, or > (MDN).
  • DOM does not validate which attributes belong on which elements (MDN).
  • For namespaced attributes, use createAttributeNS().
  • Related: setAttribute(), setAttributeNode(), attributes.

Browser Support

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

Baseline Widely available

Document.createAttribute()

Creates Attr nodes — supported across all major browsers.

Baseline Widely available
Google Chrome Supported
Yes
Mozilla Firefox Supported
Yes
Apple Safari Supported
Yes
Microsoft Edge Supported
Yes
Opera Supported
Yes
Internet Explorer Supported (legacy)
Yes
createAttribute() Wide

Bottom line: Use createAttribute when you need an Attr node; use setAttribute for everyday attribute updates.

Conclusion

document.createAttribute(localName) creates a detached Attr node. Set attr.value, attach with setAttributeNode(), and read the result with getAttribute(). For most apps, element.setAttribute() is simpler — but knowing createAttribute() helps when you work with attribute nodes directly.

Continue with createAttributeNS(), setAttribute(), or the JavaScript hub.

💡 Best Practices

✅ Do

  • Use setAttribute() for simple name/value pairs
  • Set attr.value before setAttributeNode()
  • Expect localName to be lowercased (MDN)
  • Use createAttributeNS() for SVG/XML namespaces
  • Validate attribute names to avoid exceptions

❌ Don’t

  • Assume any attribute is valid on any element (MDN)
  • Use invalid characters in localName
  • Forget to attach the detached Attr node
  • Reach for createAttribute when setAttribute suffices
  • Confuse with createElement() (creates elements, not attributes)

Key Takeaways

Knowledge Unlocked

Five things to remember about createAttribute()

Builds Attr nodes for the DOM.

5
Core concepts
🔗02

Attach

setAttributeNode

step 3
📄03

Name

lowercase

MDN
04

Prefer

setAttribute

daily
🛡05

Status

Baseline

2015

❓ Frequently Asked Questions

MDN: Document.createAttribute() creates a new attribute node — an Attr object. You set its value, then attach it to an element with setAttributeNode().
No. MDN marks Document.createAttribute() as Baseline Widely available (since July 2015). It is not Deprecated, Experimental, or Non-standard.
An Attr node (MDN). The localName parameter initializes the attribute's name; assign attr.value before attaching it.
For everyday code, element.setAttribute(name, value) is simpler. Use createAttribute() when you need an Attr node object — for example before calling setAttributeNode() or when working with attribute nodes directly.
Yes (MDN). The localName string is converted to lowercase when the Attr node is created.
MDN: the name must have at least one character and may not contain ASCII whitespace, NULL, /, =, or >. An invalid name throws an exception.
Did you know?

MDN’s basic example uses a custom attribute name my_attrib — the DOM lets you create it even though it is not a standard HTML attribute. Browsers still store and return the value once you attach it with setAttributeNode().

Next: createAttributeNS()

Learn how to create namespaced Attr nodes with namespaceURI and qualifiedName.

createAttributeNS() →

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.

6 people found this page helpful