Home  »  CodeProgrammingSnippetsTechnology   »   How to get Data Attribute in Vanilla JavaScript

How to get Data Attribute in Vanilla JavaScript

Posted: August 3, 2022 | by Michael Bright

Take this data attribute as an example.

<div id="element" class="element" data-name="Mary"></div>

Here is the JavaScript you can use to access the data attribute.

var element = document.querySelector('.element');
var dataAttribute = element.getAttribute('data-attribute');

In the above snippet replace “data-name” with your data attribute name

Alternate:

const el = document.querySelector('#element')
el.dataset.name // 'Mary'

Found this article interesting? Follow Brightwhiz on Facebook, Twitter, and YouTube to read and watch more content we post.