Repository navigation
Expand file tree
/
Copy pathindex.md
More file actions
67 lines (47 loc) · 1.64 KB
/
Copy pathindex.md
File metadata and controls
67 lines (47 loc) · 1.64 KB
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
---
title: "Storage: getItem() method"
short-title: getItem()
slug: Web/API/Storage/getItem
page-type: web-api-instance-method
browser-compat: api.Storage.getItem
---
{{APIRef("Web Storage API")}}
The **`getItem()`** method of the {{domxref("Storage")}}
interface, when passed a key name, will return that key's value, or `null` if
the key does not exist, in the given `Storage` object.
## Syntax
```js-nolint
getItem(keyName)
```
### Parameters
- `keyName`
- : A string containing the name of the key you want to retrieve the
value of.
### Return value
A string containing the value of the key. If the key does not exist,
`null` is returned.
## Examples
The following function retrieves three data items from local storage, then uses them to
set custom styles on a page.
```js
function setStyles() {
const currentColor = localStorage.getItem("bgcolor");
const currentFont = localStorage.getItem("font");
const currentImage = localStorage.getItem("image");
document.getElementById("bgcolor").value = currentColor;
document.getElementById("font").value = currentFont;
document.getElementById("image").value = currentImage;
htmlElem.style.backgroundColor = `#${currentColor}`;
pElem.style.fontFamily = currentFont;
imgElem.setAttribute("src", currentImage);
}
```
> [!NOTE]
> To see this used within a real-world example, see our [Web Storage Demo](https://mdn.github.io/dom-examples/web-storage/).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Storage.setItem()](/en-US/docs/Web/API/Storage/setItem)
- [Using the Web Storage API](/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API)