Dom Namednodemap
## XML/HTML DOM - The NamedNodeMap Object
The `NamedNodeMap` interface represents a collection of unordered nodes that can be accessed by their name or index.
While it behaves similarly to an array, a `NamedNodeMap` is **not** an array. Its primary use case in modern web development is representing the attributes of an HTML or XML element (via the `Element.attributes` property).
---
## Key Characteristics
* **Unordered Collection:** Unlike a `NodeList`, the nodes inside a `NamedNodeMap` are not stored in any guaranteed order.
* **Live Object:** A `NamedNodeMap` is "live." If attributes are added, modified, or removed from the associated element, the map automatically updates itself in real-time.
* **Key-Value Access:** Nodes can be retrieved directly by their string name (e.g., attribute name) or by their index.
---
## Properties
| Property | Type | Description |
| :--- | :--- | :--- |
| `length` | `unsigned long` | Returns the total number of nodes (attributes) currently in the map. |
---
## Methods
| Method | Return Type | Description |
| :--- | :--- | :--- |
| `getNamedItem(name)` | `Attr` | Returns the node with the specified name, or `null` if it does not exist. |
| `getNamedItemNS(namespace, localName)` | `Attr` | Returns the node with the specified local name and namespace URI. |
| `item(index)` | `Attr` | Returns the node at the specified index. Returns `null` if the index is out of bounds. |
| `removeNamedItem(name)` | `Attr` | Removes the node with the specified name and returns the removed node. |
| `removeNamedItemNS(namespace, localName)` | `Attr` | Removes the node specified by local name and namespace URI, and returns it. |
| `setNamedItem(node)` | `Attr` | Adds/replaces a node using its `nodeName` attribute. Returns the replaced node, or `null`. |
| `setNamedItemNS(node)` | `Attr` | Adds/replaces a node using its namespace URI and local name. |
---
## Code Examples
### 1. Accessing Attributes by Name and Index
The following example demonstrates how to retrieve a `NamedNodeMap` of an element's attributes and access them using both `getNamedItem()` and `item()`.
```html
NamedNodeMap Example
```
### 2. Iterating Through a NamedNodeMap
Because `NamedNodeMap` is not an array, you cannot use array methods like `forEach`, `map`, or `filter` directly. However, you can iterate through it using a standard `for` loop or by converting it to an array.
```javascript
const button = document.getElementById("myButton");
const attributes = button.attributes;
// Method A: Standard for loop
for (let i = 0; i < attributes.length; i++) {
const attr = attributes.item(i);
console.log(`${attr.name} = "${attr.value}"`);
}
// Method B: Converting to an Array using Array.from()
Array.from(attributes).forEach(attr => {
console.log(`Array iteration: ${attr.name} = "${attr.value}"`);
});
```
### 3. Adding and Removing Attributes Dynamically
You can manipulate attributes directly within the map using `setNamedItem()` and `removeNamedItem()`.
```javascript
const button = document.getElementById("myButton");
const attributes = button.attributes;
// Remove the "disabled" attribute
const removedAttr = attributes.removeNamedItem("disabled");
console.log("Removed attribute:", removedAttr.name); // Output: "disabled"
// Create and add a new attribute node
const newAttr = document.createAttribute("data-role");
newAttr.value = "submit-button";
attributes.setNamedItem(newAttr);
console.log(button.outerHTML);
// Output:
```
---
## Considerations and Best Practices
1. **Prefer Standard Element Methods:**
For modern web development, using `Element.getAttribute()`, `Element.setAttribute()`, and `Element.removeAttribute()` is generally preferred over interacting directly with the `NamedNodeMap` via `Element.attributes`. The standard element methods are cleaner and more performant:
```javascript
// Instead of this:
element.attributes.getNamedItem("class").value = "active";
// Do this:
element.setAttribute("class", "active");
```
2. **Index Order is Unreliable:**
Never write code that assumes a specific attribute is at a specific index (e.g., assuming `attributes.item(0)` is always the `id`). The browser does not guarantee any specific order for attributes inside a `NamedNodeMap`.
3. **Live Object Performance:**
Because the map is live, querying its `length` property inside a loop condition can cause performance overhead in very large DOM trees. Cache the length in a variable if you are performing heavy iterations.
YouTip