JavaScriptのgetAttribute()でHTML属性の値を取得する

element.getAttribute(name)はHTML属性の値を文字列で返し、属性がなければnullを返します。フォームでの現在値はマークアップと異なる場合があるため、checkedやvalueなどのDOMプロパティで読み取ります。

構文と戻り値を確認する

const link = document.getElementById("guide");

if (link !== null) {
  const href = link.getAttribute("href");
  console.log(href);
}

getAttribute()は要素に対して呼び出します。getElementById()がnullを返したら、選択方法と実行時点を確認します。DOM(Document Object Model)はページをオブジェクトで表現します。要素がない場合と属性がない場合は別です。

空の属性と存在しない属性を区別する

const title = element.getAttribute("title");

if (title === null) {
  console.log("The title attribute is missing.");
} else if (title === "") {
  console.log("The title attribute is empty.");
} else {
  console.log(title);
}

if (title)では空文字列もnullも偽になります。存在だけを調べるにはhasAttribute()を使います。data-*の値も文字列です。datasetではdata-user-idをdataset.userIdとして読めます。

hrefとcheckedを完全な例で比較する

コードをget-attribute.htmlとして保存し、開きます。リンクは同じ文書の見出しを指します。最初はチェック済みで、スクリプトは要素より後ろにあります。

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Read HTML attributes and state</title>
</head>
<body>
<h1>Read attributes</h1>
<p><a id="guide" href="#details" title="" data-count="3">Go to details</a></p>
<label><input id="agree" type="checkbox" checked> Acknowledge notice</label>
<pre id="output"></pre>
<h2 id="details">Details</h2>
<p>Uncheck and recheck the box to compare the results.</p>
<script>
const guide = document.getElementById("guide");
const agree = document.getElementById("agree");
const output = document.getElementById("output");
function render() {
  output.textContent = [
    `href attribute: ${guide.getAttribute("href")}`,
    `href property: ${guide.href}`,
    `title: ${JSON.stringify(guide.getAttribute("title"))}`,
    `missing aria-label: ${JSON.stringify(guide.getAttribute("aria-label"))}`,
    `data-count type: ${typeof guide.getAttribute("data-count")}`,
    `checked attribute: ${JSON.stringify(agree.getAttribute("checked"))}`,
    `current checked: ${agree.checked}`
  ].join("\n");
}
agree.addEventListener("change", render);
render();
</script>
</body>
</html>

初期値はhref属性が#details、titleが""、存在しないaria-labelがnullです。data-countの型はstringです。hrefプロパティは基準URLで解決したアドレスを返します。チェックを外すとcheckedはfalseになりますが、空の属性は残ります。title=""を一時的に削除して再読み込みすると欠落時と比較できます。

属性値をそのまま文字として表示する

&lt;のような文字参照はHTML解析後に<になります。マークアップとして解釈せず表示するにはtextContentを使います。属性の変更と削除にはsetAttribute()とremoveAttribute()を使い、現在の入力状態には適切なプロパティを使います。

const label = element.getAttribute("data-label");
output.textContent = label ?? "";

0と欠落を区別して個数に変換する

実習ページのConsoleで次のコードを実行します。リンクを複製し、0以上の10進整数だけを受け付けます。前後の空白を除いた文字を確認してからNumber()とNumber.isSafeInteger()を使います。

{
  const example = document.querySelector("#guide").cloneNode();

  function readCount(element) {
    const raw = element.getAttribute("data-count");
    if (raw === null || !/^[0-9]+$/.test(raw.trim())) return null;

    const count = Number(raw);
    return Number.isSafeInteger(count) ? count : null;
  }

  console.log(readCount(example)); // 3
  example.setAttribute("data-count", "0");
  console.log(readCount(example)); // 0
  example.setAttribute("data-count", " ");
  console.log(readCount(example)); // null
  example.removeAttribute("data-count");
  console.log(readCount(example)); // null
}

3、0、null、nullと表示されます。空白だけの値は0に変換されません。負数、小数、16進表記、安全な整数の範囲外もnullです。有効な0を保つにはcount === nullを確認します。