{"id":12258,"date":"2022-08-03T12:04:43","date_gmt":"2022-08-03T16:04:43","guid":{"rendered":"http:\/\/local.brightwhiz\/?post_type=snippets&p=12258"},"modified":"2022-08-03T12:04:46","modified_gmt":"2022-08-03T16:04:46","slug":"get-data-attribute-in-vanilla-javascript","status":"publish","type":"snippets","link":"http:\/\/local.brightwhiz\/snippets\/get-data-attribute-in-vanilla-javascript\/","title":{"rendered":"How to get Data Attribute in Vanilla JavaScript"},"content":{"rendered":"\n
Take this data attribute as an example.<\/p>\n\n\n\n
<div id="element" class="element" data-name="Mary"><\/div><\/code><\/pre>\n\n\n\nHere is the JavaScript you can use to access the data attribute.<\/p>\n\n\n\n
var element = document.querySelector('.element');\nvar dataAttribute = element.getAttribute('data-attribute');<\/code><\/pre>\n\n\n\nIn the above snippet replace “data-name” with your data attribute name<\/p>\n\n\n\n
Alternate:<\/p>\n\n\n\n
const el = document.querySelector('#element')\nel.dataset.name \/\/ 'Mary'<\/code><\/pre>\n","protected":false},"comment_status":"open","ping_status":"closed","template":"","meta":[],"categories":[953,27,15,16],"tags":[303,328,433,471],"yoast_head":"\nHow to get HTML Element Data Attribute in Vanilla JavaScript<\/title>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\n