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.

4 min read

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.

htmlhtml
<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:

javascriptjavascript
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:

javascriptjavascript
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.

javascriptjavascript
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.

htmlhtml
<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:

javascriptjavascript
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 typeUse this
Custom data-* attributesdataset
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:

htmlhtml
<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:

javascriptjavascript
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

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.
RunePowered by Rune AI

Frequently Asked Questions

What is the difference between attributes and properties?

Attributes are defined in the HTML markup. Properties are the JavaScript object representations. For most standard attributes like id, class, and href, the attribute and property stay in sync. For some, like the value of an input, the property reflects the current state while the attribute reflects the initial value.

How does the dataset API handle hyphenated data attributes?

data-user-id becomes dataset.userId. The data- prefix is removed, and any hyphens are converted to camelCase. So data-product-category becomes dataset.productCategory. The conversion is automatic and consistent.

Can I store objects in data attributes?

data attributes only store strings. To store an object, serialize it with JSON.stringify when setting and parse with JSON.parse when reading. For large or complex data, consider storing an ID in the data attribute and keeping the actual data in a JavaScript object or Map.

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.