how to get data attr javascript code example

Example 1: javascript get data-id attribute

//get data-id attribute in plain Javascript
var element = document.getElementById('myDivID');
var dataID = element.getAttribute('data-id');

//get data-id using jQuery
var dataID = $('myDivID').data('data-id');

Example 2: get data attribute javascript

// <div id="element" data-name="john"></div>

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

Tags:

Java Example