DOM Attributes Dataset and Custom Data in JavaScript
Learn to read, set, and remove HTML attributes with JavaScript. Covers getAttribute, setAttribute, the dataset API for data-* attributes, and when to use each.
DOM attributes in JavaScript carry metadata and configuration on elements: an image's source, a link's destination, a form input's type. JavaScript lets you read, change, add, and remove these attributes at any time.
For standard attributes like href and src, use getAttribute and setAttribute. For your own custom data, the dataset API provides a cleaner, dedicated interface.
<img id="photo" src="default.jpg" alt="A placeholder image">The img element has two standard attributes: src pointing to an image file, and alt providing fallback text. From JavaScript, you can read the current source and replace it with a different image:
const img = document.querySelector("#photo");
console.log(img.getAttribute("src"));
img.setAttribute("src", "new-photo.jpg");The image source changes from "default.jpg" to "new-photo.jpg". The browser loads the new image and updates the display. The alt attribute remains unchanged.
Reading and Setting Standard Attributes
getAttribute takes an attribute name as a string and returns its value. If the attribute does not exist, it returns null.
setAttribute takes a name and a value, creating the attribute if it is new or updating it if it already exists. Both methods work on any standard HTML attribute.
Here is how to read a link's destination and set additional attributes on the same element:
const link = document.querySelector("a");
const target = link.getAttribute("href");
link.setAttribute("target", "_blank");
link.setAttribute("rel", "noopener noreferrer");The link now opens in a new tab with the security attributes set. Each setAttribute call modifies exactly one attribute without disturbing the others on the same element. For boolean attributes like disabled, checked, and readonly, prefer the element property directly: button.disabled = true is clearer than setAttribute("disabled", "").
Removing Attributes
removeAttribute deletes an attribute from an element entirely. After removal, getAttribute returns null for that name.
const input = document.querySelector("#email");
input.removeAttribute("disabled");The input becomes editable again. This is useful for enabling form fields after validation passes or after a loading state completes.
The dataset API: Custom Data Attributes
HTML5 introduced data-* attributes for storing custom data directly in HTML. The dataset API gives you a clean way to read and write these attributes from JavaScript without using getAttribute and setAttribute.
<article
id="post-1"
data-author="Jane Doe"
data-category="tech"
data-publish-date="2026-07-15"
>
Article content here.
</article>This article element carries three custom data attributes: the author name, the post category, and the publication date. The dataset API lets you read all three with a clean, dot-notation syntax that automatically handles the hyphen-to-camelCase naming conversion behind the scenes:
const article = document.querySelector("#post-1");
console.log(article.dataset.author);
console.log(article.dataset.category);
console.log(article.dataset.publishDate);The dataset API automatically converts hyphenated attribute names to camelCase. So data-publish-date becomes dataset.publishDate, and data-user-id becomes dataset.userId. The data- prefix is always stripped, and each hyphen marks the start of a new uppercase letter.
Writing values works the same way. Assign a string to a dataset property like dataset.viewCount = "42" and the corresponding data-view-count attribute updates on the element. The browser keeps attributes and dataset properties synchronized in both directions.
When to Use dataset vs getAttribute
Here is the quick rule for choosing between the two:
| Attribute type | Use this |
|---|---|
| Custom data-* attributes | dataset |
| Standard attributes (href, src, id, class) | getAttribute/setAttribute, or a direct property |
For data-* attributes, dataset is the cleaner choice because the name conversion is automatic and the API reads more naturally. For standard HTML attributes, getAttribute and setAttribute work everywhere, but a direct property like element.href or element.src is often even simpler.
A common pattern is storing an element's database ID in a data attribute so your click handler knows which record to update:
<button data-id="42" class="delete-btn">Delete</button>This button carries its database key directly in the markup, with no extra lookup needed. Read that key inside a click handler attached to every matching button:
document.querySelectorAll(".delete-btn").forEach((btn) => {
btn.addEventListener("click", () => {
const recordId = btn.dataset.id;
console.log("Deleting record:", recordId);
});
});The button's data-id attribute carries the database key. The click handler reads it through dataset.id and uses it to identify which record to delete.
Where to Go Next
Attributes work closely with selecting DOM elements, where attribute selectors like [data-id] are a powerful way to find elements. For building interactive features on top of your data attributes, see handling click events in JavaScript.
Rune AI
Key Insights
- getAttribute reads an attribute value; setAttribute sets or updates one.
- The dataset API gives direct access to all data-* attributes.
- Data attribute names convert from hyphen-case to camelCase in dataset.
- removeAttribute deletes an attribute entirely from the element.
- Attributes are strings; use JSON.stringify for storing objects.
Frequently Asked Questions
What is the difference between attributes and properties?
How does the dataset API handle hyphenated data attributes?
Can I store objects in data attributes?
Conclusion
Attributes connect your HTML and JavaScript. Use getAttribute and setAttribute for standard HTML attributes like href, src, and alt. Use the dataset API for your own custom data attributes. Use removeAttribute to clean up attributes you no longer need. Together these methods give you full control over every attribute on every element.
More in this topic
Using Decorators for Logging in JS Architecture
Learn how JavaScript decorators wrap class methods to add logging without touching the original code, including setup with Babel and how execution order works.
JavaScript While Loop Explained: A Complete Guide
A while loop repeats code as long as a condition stays true. Learn the syntax, see practical examples, and understand when a while loop is the right choice over a for loop.
JavaScript Loops Tutorial: for, while, do while
Loops let JavaScript repeat code without writing it twice. Learn the three core loop types, what each one does, and when to choose one over another.