English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Storage setItem() Method

JavaScript Storage Object

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.

Syntax:

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‹/›

Browser compatibility

The numbers in the table specify the first browser version that fully supports the setItem() method:

Method
setItem()43.511.549

Parameter value

ParameterDescription
keyContaining the to be created/The string containing the name of the key to be updated
valueContaining the to be provided/The string value of the updated key

Technical details

Return value:A string representing the inserted value
DOM version:Web Storage API

More examples

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‹/›

Related References

HTML Tutorial:Web Storage API

Reference for Window (Window):window.localStorage property

Reference for Window (Window):window.sessionStorage property

JavaScript Storage Object