English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
setItem()This method sets the value of the specified key name in the given storage object, and if the key value already exists, it updates the key value.
The setItem() method of the storage object can belocalStorageObject orsessionStorrageObject.
localStorage.setItem(key, value)
sessionStorage.setItem(key, value)
;localStorage.setItem('color', 'green'); ;localStorage.setItem('image', 'parrot.png'); ;localStorage.setItem('url', 'https://www.oldtoolbag.com');Test and See‹/›
The numbers in the table specify the first browser version that fully supports the setItem() method:
Method | |||||
setItem() | 4 | 3.5 | 11.5 | 4 | 9 |
Parameter | Description |
---|---|
key | Containing the to be created/The string containing the name of the key to be updated |
value | Containing the to be provided/The string value of the updated key |
Return value: | A string representing the inserted value |
---|---|
DOM version: | Web Storage API |
Set the value of the specified session storage item:
sessionStorage.setItem('time', Date.now()); sessionStorage.setItem('age', 22);Test and See‹/›
You can also use dot notation to set values:
localStorage.color = "green"; localStorage.image = "parrot.png"; localStorage.url = "https://www.oldtoolbag.com";Test and See‹/›
The following function creates three data items in local storage and then uses them to set custom styles on the page:
function populateStorage() { ;localStorage.setItem('bgcolor', document.getElementById('bgcolor').value); ;localStorage.setItem('font', document.getElementById('font').value); ;localStorage.setItem('image', document.getElementById('image').value); }Test and See‹/›
HTML Tutorial:Web Storage API
Reference for Window (Window):window.localStorage property
Reference for Window (Window):window.sessionStorage property