How to Get a data-* Attribute from an Element
A quick guide on how to access data-* attributes from an HTML element in TypeScript using the dataset property.
A great way to store extra information on an HTML element is to use custom
data-* attributes. You can easily read these values in TypeScript.
Imagine you have a search input that needs to know which “cookbook” it belongs to. You can store this information directly on the element.
HTML
<input
id="search-input"
type="text"
placeholder="Search"
data-cookbook-id="typescript"
/>In TypeScript, you can get this value from the element’s dataset property.
TypeScript
const searchInput = document.querySelector<HTMLInputElement>("#search-input");
if (searchInput) {
// Access the data attribute
const cookbookId = searchInput.dataset.cookbookId;
console.log("Cookbook ID from data-* attribute:", cookbookId);
// Expected output: "typescript"
}How it works:
data-cookbook-id: In HTML, the attribute is written inkebab-case.searchInput.dataset.cookbookId: In TypeScript, thedatasetproperty converts the attribute name tocamelCase. So,data-cookbook-idbecomescookbookId.
The value you get from dataset will always be a string. If the attribute
doesn’t exist, it will be undefined.