Get the name of the first attributes of an element:
const nodeMap = document.getElementById("myDiv").attributes;
let name1 = nodeMap.item(0).name;
let name2 = nodeMap.item(1).name;
Try it Yourself »
const nodeMap = document.getElementById("myDiv").attributes;
let name1 = nodeMap[0].name;
let name2 = nodeMap[1].name;
Try it Yourself »
More examples below.
The item()
method returns an attribute (by index) from a NamedNodeMap.
The nodes are sorted as they appear in the source code. The index starts at 0.
namednodemap.item(
index)
or simply:
namednodemap[
index]
Parameter | Description |
index | Required. The index of the attribute node in the NamedNodeMap. |
Type | Description |
A node | The attribute node at the specified index. Or null if the index number is out of range. |
Change the class (the color) of an element:
document.getElementById("myDiv").attributes.item(1).value = "class2";
Try it Yourself »
Change the class (the color) of an element:
document.getElementById("myDiv").attributes[1].value = "class2";
Try it Yourself »
attributes.item()
is a DOM Level 1 (1998) feature.
It is fully supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | 9-11 |
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!