Storage: getItem() メソッド

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 Standard
# dom-storage-getitem-dev

ブラウザーの互換性

BCD tables only load in the browser

関連情報