DEV Community

Victor Olaoye
Victor Olaoye

Posted on • Originally published at Medium on

How To Access And Render Data Attributes With CSS & JavaScript


Photo by Goran Ivos on Unsplash

Data attributes gives us the ability to embed custom data attributes in HTML. According to MDN, data attributes allows us to store extra information on standard semantic HTML elements without other hacks such as non-standard attributes, or extra properties on DOM.

The beauty of these data attributes is that, it can be accessed in CSS and JavaScript. Let’s see an example of how it works with CSS first:

<b data-content="John Doe"></b>
<style type="text/css">
  b::after{
       content: attr(data-content);
  }
</style>
Enter fullscreen mode Exit fullscreen mode

From the above CSS code block, we can see that the ::after pseudo-class selector uses content property to render the data attribute. In this context, it renders “John Doe” as the data content.

Also, JavaScript can be used to access and render data attributes on the web page. Let’s see an example below:

var name = b.document.getElementById("name");

console.log(name.dataset.parent);
Enter fullscreen mode Exit fullscreen mode

From the example above, we can see that the data attribute is being accessed with the dataset property and then logged onto the console.

Notable References

Top comments (0)