Storage: getItem() メソッド

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

getItem()Storage インターフェイスのメソッドで、キーの名称を渡すと、そのキーに対する値を返します。指定された Storage オブジェクトにそのキーが存在しない場合は null を返します。

構文

js
getItem(keyName)

引数

keyName

文字列で、値を取り出したいキーの名前を指定します。

返値

キーに対する値を持つ文字列です。キーが存在しない場合は null が返ります。

以下の関数はローカルストレージから 3 個のデータアイテムを取り出して、その値を使用してページのカスタムスタイルを設定します。

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);
}

メモ: 現実世界の例として、Web Storage Demo をご覧ください。

仕様書

Specification
HTML
# dom-storage-getitem-dev

ブラウザーの互換性

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Deno
getItem

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

関連情報