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(文档对象模型)用对象表示页面。没有元素和元素没有某个属性是两种情况。

区分空属性和缺失属性

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,空的 checked 标记仍存在。临时删除 title="" 并重新加载可以比较缺失状态。

将属性值作为纯文本显示

HTML 解析会将 &lt; 等字符引用转换为 <。用 textContent 将读取的值作为文字显示。使用 setAttribute() 和 removeAttribute() 修改标记属性。读取表单当前状态时,使用相应的 DOM 属性。

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

把属性转换为计数并保留 0

在示例页的 Console 中执行以下代码。它克隆链接,只接受非负十进制整数。先检查去掉首尾空白的字符串,再调用 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,负数、小数、十六进制写法和超出安全整数范围的值也会得到 null。用 count === null 检查失败,才能保留有效的 0。