-
Notifications
You must be signed in to change notification settings - Fork 22.4k
/
index.md
90 lines (61 loc) · 1.96 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
---
title: "Element: getAttribute() method"
short-title: getAttribute()
slug: Web/API/Element/getAttribute
page-type: web-api-instance-method
browser-compat: api.Element.getAttribute
---
{{APIRef("DOM")}}
The **`getAttribute()`** method of the
{{domxref("Element")}} interface returns the value of a specified attribute on the
element.
If the given attribute does not exist, the value returned will be `null`.
If you need to inspect the {{domxref("Attr")}} node's properties, you can use the {{domxref("Element.getAttributeNode()", "getAttributeNode()")}} method instead.
## Syntax
```js-nolint
getAttribute(attributeName)
```
### Parameters
- `attributeName` is the name of the attribute whose value you want to get.
### Return value
A string containing the value of `attributeName` if the attribute exists, otherwise `null`.
## Examples
```html
<!-- example div in an HTML DOC -->
<div id="div1">Hi Champ!</div>
```
```js
// in a console
const div1 = document.getElementById("div1");
//=> <div id="div1">Hi Champ!</div>
const exampleAttr = div1.getAttribute("id");
//=> "div1"
const align = div1.getAttribute("align");
//=> null
```
## Description
### Lower casing
When called on an HTML element in a DOM flagged as an HTML document,
`getAttribute()` lower-cases its argument before proceeding.
### Retrieving nonce values
For security reasons, [CSP](/en-US/docs/Web/HTTP/CSP) nonces from non-script
sources, such as CSS selectors, and `.getAttribute("nonce")` calls are
hidden.
```js example-bad
let nonce = script.getAttribute("nonce");
// returns empty string
```
Instead of retrieving the nonce from the content attribute, use the
{{domxref("HTMLElement/nonce", "nonce")}} property:
```js
let nonce = script.nonce;
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("Element.hasAttribute()")}}
- {{domxref("Element.setAttribute()")}}
- {{domxref("Element.removeAttribute()")}}
- {{domxref("Element.toggleAttribute()")}}