--- title: HTMLElement.dataset slug: Web/API/HTMLElement/dataset tags: - API - HTML DOM - HTMLElement - Tham khảo - Thuộc tính - dataset translation_of: Web/API/HTMLOrForeignElement/dataset ---
{{ APIRef("HTML DOM") }}

The dataset property on the {{domxref("HTMLElement")}} interface provides read/write access to all the custom data attributes (data-*) set on the element. This access is available both in HTML and within the DOM.  It is a map of DOMString, one entry for each custom data attribute.  Note that the dataset property itself can be read, but not directly written.  Instead, all writes must be to the individual properties within the dataset, which in turn represent the data attributes.   Note also that an HTML data-attribute and its corresponding DOM dataset.property do not share the same name, but they are always similar:

In addition to the information below, you'll find a how-to guide for using HTML data attributes in our article Using data attributes.

Chuyển đổi tên

Từ dash-style (kiểu-gạch-nối) sang camelCase (bướuLạcĐà): Tên thuộc tính dữ liệu tùy biến được chuyển đổi thành khóa cho {{ domxref("DOMStringMap") }} dự trên quy định sau:

Từ camelCase (bướuLạcĐà) sang dash-style (kiểu-gạch-nối): Cách chuyển đổi ngược lại, dò theo khóa để tìm ra tên thuộc tính, bằng quy định sau:

Việc có rằng buộc trong quy định trên nhằm đảm bảo việc chuyển đổi có thể đảo ngược cho nhau.

Ví dụ, thuộc tính có tên data-abc-def sẽ có khóa tương ứng abcDef.

Truy cập giá trị

Loại giá trị

Cú pháp

Ví dụ

<div id="user" data-id="1234567890" data-user="johndoe" data-date-of-birth>John Doe</div>
const el = document.querySelector('#user');

// el.id == 'user'
// el.dataset.id === '1234567890'
// el.dataset.user === 'johndoe'
// el.dataset.dateOfBirth === ''

// gán dữ liệu cho thuộc tính data
el.dataset.dateOfBirth = '1960-10-03';
// Kết quả: el.dataset.dateOfBirth === 1960-10-03

delete el.dataset.dateOfBirth;
// Kết quả: el.dataset.dateOfBirth === undefined

// 'someDataAttr' in el.dataset === false
el.dataset.someDataAttr = 'mydata';
// Kết quả: 'someDataAttr' in el.dataset === true

Thông số kỹ thuật

Thông số kỹ thuật Trạng thái Chú thích
{{SpecName('HTML WHATWG', "dom.html#dom-dataset", "HTMLElement.dataset")}} {{Spec2('HTML WHATWG')}} No change from latest snapshot, {{SpecName('HTML5.1')}}
{{SpecName('HTML5.1', "dom.html#dom-dataset", "HTMLElement.dataset")}} {{Spec2('HTML5.1')}} Snapshot of {{SpecName('HTML WHATWG')}}, no change from {{SpecName('HTML5 W3C')}}
{{SpecName('HTML5 W3C', "dom.html#dom-dataset", "HTMLElement.dataset")}} {{Spec2('HTML5 W3C')}} Snapshot of  {{SpecName('HTML WHATWG')}}, initial definition.

Tính tương thích trên trình duyệt

{{Compat("api.HTMLElement.dataset")}}

Xem thêm