Element: getAttribute() method

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.

Thuộc tính getAttribute() method of the Element interface trả về the value of a specified attribute on the element.

If the given attribute does not exist, the value returned will be null.

If you need to inspect the Attr node's properties, you can use the getAttributeNode() method instead.

Cú pháp

js
getAttribute(attributeName)

Tham số

attributeName

The name of the attribute whose value you want to get.

Giá trị trả về

Một chuỗi chứa the value of attributeName if the attribute exists, otherwise null.

Ví dụ

html
<!-- example div in an HTML DOC -->
<div id="div1">Hi Champ!</div>
js
const div1 = document.getElementById("div1");
// <div id="div1">Hi Champ!</div>

const exampleAttr = div1.getAttribute("id");
// "div1"

const lang = div1.getAttribute("lang");
// null

Mô tả

Lower casing

When called on an HTML element in a DOM flagged as an HTML document, getAttribute() lower-cases its argument before proceeding.

Retrieving nonce values

For security reasons, CSP nonces from non-script sources, such as CSS selectors, and .getAttribute("nonce") calls are hidden.

js
let nonce = script.getAttribute("nonce");
// trả về empty string

Instead of retrieving the nonce from the content attribute, use the nonce property:

js
let nonce = script.nonce;

Đặc tả kỹ thuật

Specification
DOM
# ref-for-dom-element-getattribute①

Trình duyệt hỗ trợ

Xem thêm