-
Notifications
You must be signed in to change notification settings - Fork 22.4k
/
index.md
74 lines (52 loc) · 1.69 KB
/
index.md
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
---
title: "NamedNodeMap: setNamedItem() method"
short-title: setNamedItem()
slug: Web/API/NamedNodeMap/setNamedItem
page-type: web-api-instance-method
browser-compat: api.NamedNodeMap.setNamedItem
---
{{APIRef("DOM")}}
The **`setNamedItem()`** method of the {{domxref("NamedNodeMap")}} interface
puts the {{domxref("Attr")}} identified by its name in the map.
If there is already an {{domxref("Attr")}} with the same name in the map,
it is _replaced_.
## Syntax
```js-nolint
setNamedItem(attr)
```
### Parameters
- `attr`
- : the attribute to insert in the map.
### Return value
Returns the old attribute if replaced, or `null` if the attribute is new.
### Exceptions
- `InUseAttributeError` {{domxref("DOMException")}}
- : Thrown if the attribute is still part of another map.
## Example
```html
<span one="one" two="two"></span>
<pre test="testValue"></pre>
```
```js
const span = document.querySelector("span");
const pre = document.querySelector("pre");
const attrMap = pre.attributes;
let result = `The '<pre>' element initially contains ${attrMap.length} attributes.\n\n`;
result += "We remove `one` from `<span>` and adds it to `<pre>`.\n";
const one = span.attributes.removeNamedItem("one");
attrMap.setNamedItem(one);
result += `The '<pre>' element now contains ${pre.attributes.length} attributes.\n\n`;
result += "We get 'two' from '<span>' and try to adds it to '<pre>'.\n";
const two = span.attributes.getNamedItem("two");
try {
attrMap.setNamedItem(two);
} catch (error) {
result += `An exception has been raised: ${error.name}.\n`;
}
pre.textContent = result;
```
{{EmbedLiveSample("Example", "100%", 160)}}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}