How to Access Data Easily in Javascript

Jennifer Yoo
Sep 8 · 2 min read

In Javascript, it can be difficult to access specific data in HTML by traversing the Document Object Model and using that data in your Javascript functions. Introducing, datasets.

Image for post
Image for post

Dataset is a read-only property of the HTML interface that provides access to all the custom data attributes set on the element. You can store data inside the elements so it can be easily available for a later function.

In HTML, the custom dataset attribute is set by using data- followed by the custom attribute.

<p class="like-info" data-user-id="1">20 Likes</p>

The name of the dataset must only contain lowercase letters, numbers, dash (-), dot (.), colon (:), or underscore (_). The value of the dataset is also always a string.

In Javascript, the custom dataset attribute is set by using .dataset

const pTag = document.querySelector(".like-info")

The name of the dataset must contain camelCase or numbers with no dashes, dots, etc.

It is important to keep in mind that the dataset value will be stored as a string in HTML even if the number saved was an integer.

Accessing dataset values

In Javascript, to locate a specific data attribute using querySelector, you will need to enclose “data-attribute=” in brackets.

document.querySelector(`[data-attribute=“${data}”]`)

There is a much easier way to do this if the syntax above is a bit confusing. You can access the element’s dataset by following the code below.

<p class="like-info" data-user-id="1">20 Likes</p>

Altering Datasets

You also have the option to delete a dataset. Using the delete keyword before your custom dataset attribute will result in an undefined value.

delete pTag.dataset.userId

There are also instances where you may to alter your dataset value. This is easily done by setting the new value equal to your dataset attribute.

<p class="like-info" data-user-id="1">20 Likes</p>
Image for post
Image for post

I hope this helps you along on your javascript coding journey!

The Startup

Medium's largest active publication, followed by +720K people. Follow to join our community.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store