What are HTML5 data attributes?
Aug 06, 2025 pm 05:39 PMHTML5 data attributes are custom, valid HTML attributes used to store extra information in elements for JavaScript or CSS. 1. They are defined as data-* attributes, like data-user-id="123". 2. They allow embedding private, custom data directly in markup without affecting layout or behavior. 3. Use them to pass server data to scripts, store metadata, or avoid global variables and extra AJAX requests. 4. Access them in JavaScript via the dataset property, where data-last-login becomes element.dataset.lastLogin (camel-cased). 5. Alternatively, use getAttribute('data-role') and setAttribute('data-status', 'active'). 6. Follow best practices: only use data-* names, keep data simple and small, and avoid storing sensitive or public configuration data. They provide a standardized, framework-free way to attach usable data to elements, fully supported in modern browsers and accessible as needed during runtime.
HTML5 data attributes are custom attributes you can add to any HTML element to store extra information that can be used by JavaScript or CSS without affecting the layout or behavior of the page. They are a way to embed custom, private data directly into your markup in a standardized, valid way.

They follow a simple naming pattern: *`data-**, where the
*` is replaced with a name of your choice. For example:
<div data-user-id="123" data-role="admin" data-last-login="2023-08-01"> John Doe </div>
In this example:

data-user-id
,data-role
, anddata-last-login
are all custom data attributes.- They store extra info about the user that JavaScript can later access.
Why use data attributes?
They’re useful when you want to:
- Pass data from the server (via templates) to client-side scripts.
- Store temporary state or metadata directly on elements.
- Avoid polluting global variables or making extra AJAX requests.
How to access them in JavaScript
You can read and write data attributes using the dataset
property:

const element = document.querySelector('div'); // Read data console.log(element.dataset.userId); // "123" console.log(element.dataset.role); // "admin" // Update data element.dataset.lastLogin = '2024-05-20';
Note: The names in dataset
are camel-cased versions of the hyphenated attribute names (data-last-login
→ lastLogin
).
You can also use getAttribute()
and setAttribute()
:
element.getAttribute('data-role'); // "admin" element.setAttribute('data-status', 'active');
Rules and best practices
- Name them
data-*
only — other custom attributes aren't valid HTML. - Keep the data simple: strings, numbers, or JSON strings if needed.
- Don’t store large amounts of data — it can slow down page rendering.
- Don’t use them for public configuration or security-sensitive info.
Basically, data attributes are a clean, built-in way to attach extra info to HTML elements that you can use later in your scripts — no plugins or frameworks required.
The above is the detailed content of What are HTML5 data attributes?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

HTML5, CSS and JavaScript should be efficiently combined with semantic tags, reasonable loading order and decoupling design. 1. Use HTML5 semantic tags, such as improving structural clarity and maintainability, which is conducive to SEO and barrier-free access; 2. CSS should be placed in, use external files and split by module to avoid inline styles and delayed loading problems; 3. JavaScript is recommended to be introduced in front, and use defer or async to load asynchronously to avoid blocking rendering; 4. Reduce strong dependence between the three, drive behavior through data-* attributes and class name control status, and improve collaboration efficiency through unified naming specifications. These methods can effectively optimize page performance and collaborate with teams.

It is a block-level element, suitable for layout; it is an inline element, suitable for wrapping text content. 1. Exclusively occupy a line, width, height and margins can be set, which are often used in structural layout; 2. No line breaks, the size is determined by the content, and is suitable for local text styles or dynamic operations; 3. When choosing, it should be judged based on whether the content needs independent space; 4. It cannot be nested and is not suitable for layout; 5. Priority is given to the use of semantic labels to improve structural clarity and accessibility.

MSE (MediaSourceExtensions) is part of the W3C standard, allowing JavaScript to dynamically build media streams, thus enabling advanced video playback capabilities. It manages media sources through MediaSource, stores data from SourceBuffer, and represents the buffering time range through TimeRanges, allowing the browser to dynamically load and decode video clips. The process of using MSE includes: ① Create a MediaSource instance; ② Bind it to an element; ③ Add SourceBuffer to receive data in a specific format; ④ Get segmented data through fetch() and append it to the buffer. Common precautions include: ① Format compatibility issues; ② Time stamp pair

HTML5introducednewinputtypesthatenhanceformfunctionalityanduserexperiencebyimprovingvalidation,UI,andmobilekeyboardlayouts.1.emailvalidatesemailaddressesandsupportsmultipleentries.2.urlchecksforvalidwebaddressesandtriggersURL-optimizedkeyboards.3.num

To get the user's current location, use the HTML5 GeolocationAPI. This API provides information such as latitude and longitude after user authorization. The core method is getCurrentPosition(), which requires successful and error callbacks to be handled; at the same time, pay attention to the HTTPS prerequisite, user authorization mechanism and error code processing. ① Call getCurrentPosition to get the position once, and an error callback will be triggered if it fails; ② The user must authorize it, otherwise it cannot be obtained and may no longer be prompted; ③ Error processing should distinguish between rejection, timeout, location unavailable, etc.; ④ Enable high-precision, set timeout time, etc., and can be configured through the third parameter; ⑤ The online environment must use HTTPS, otherwise it may be restricted by the browser.

It is more convenient to submit form data using HTML5's FormData API. 1. It can automatically collect form fields with name attribute or manually add data; 2. It supports submission in multipart/form-data format through fetch or XMLHttpRequest, which is suitable for file upload; 3. When processing files, you only need to append the file to FormData and send a request; 4. Note that the same name field will be overwritten, and JSON conversion and no nesting structure need to be handled.

HTML5 tags can directly implement web page progress bars. 1. The basic usage is to set the value and max attributes, such as displaying 30% progress; 2. If the progress is unknown, the value can be omitted and only set max, which means an uncertain state; 3. You can customize the style through CSS, and browser compatibility needs to be handled; 4. It is often used in scenarios such as uploading files, form progress, and game loading; 5. Pay attention to avoid using it when the task is completed too quickly, and consider the compatibility issues of the old version of IE.

The difference between async and defer is the execution timing of the script. async allows scripts to be downloaded in parallel and executed immediately after downloading, without guaranteeing the execution order; defer executes scripts in order after HTML parsing is completed. Both avoid blocking HTML parsing. Using async is suitable for standalone scripts such as analyzing code; defer is suitable for scenarios where you need to access the DOM or rely on other scripts.
