fbpx

Get and Set Data Attributes with Javascript

We’re very familiar with getting or setting data attributes with jQuery but we had to do a little research to figure out how to get and set data attributes with Javascript. The code below show how to get and set data attributes on an HTML element with Javascript.

The HTML Element

<a href="#" class="modal" data-modal-id="modal_25" data-user="13">Click me</a>

Getting Data Attribute Values

As you can see in the code below, any data attribute that is separated by a hyphen should be referenced in camel case in your Javascript file.

var modal = document.getElementsByClassName('modal')[0];

// get the data-modal-id attribute
var modal_id = modal.dataset.modalId;
console.log(modal_id);

// get the data-user attribute
var user = modal.dataset.user;
console.log(user);

Setting Data Attribute Values

Again, make sure to reference hyphen separated data attributes in camel case in the javascript file.

var modal = document.getElementsByClassName('modal')[0];

// set the data-modal-id attribute
modal.dataset.modalId = 'modal_26';

// set the data-user attribute
modal.dataset.user = '14';

Leave a Reply

Your email address will not be published. Required fields are marked *