如何使用 JavaScript 獲取屬性的值
要獲取元素屬性的值,可以使用 getAttribute()
方法。此方法返回具有指定名稱的屬性的值。如果屬性不存在,則返回null
或一個空字符串 (""
)。
假設您有以下錨元素:
<a href="http://example.com" title="Go Back" data-role="self">Click Me</a>
現在您要獲取 href
的值 屬性。這是您可以使用的代碼片段:
const anchor = document.querySelector('a');
const href = anchor.getAttribute('href');
console.log(href); // http://example.com
getAttribute()
方法也適用於 HTML5 data-*
屬性。
例如,要獲取 data-role
的值 錨元素的屬性,可以使用 getAttribute()
方法如下:
const anchor = document.querySelector('a');
const role = anchor.getAttribute('data-role');
console.log(role); // self
如果您想將屬性的值作為 Attr
對象,使用 getAttributeNode()
替代方法:
const anchor = document.querySelector('a');
const attr = anchor.getAttributeNode('title');
console.log(attr.value); // Go Back
getAttribute()
該方法適用於所有現代瀏覽器,以及 IE9 及更高版本。