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)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay