HTML JS

GET & SET HTML DATA ATTRIBUTES IN JAVASCRIPT

SET DATA-KEY=”VALUE” IN START TAG <div id="demo" data-color=”red”></div>

SET DATA ATTRIBUTE

01

ASSIGN DATASET IN JAVASCRIPT document.getElementById("demo").dataset.color = "Red";

ELEMENT WITH DATA-KEY=”VALUE” <div id="demo" data-color=”red”></div>

GET DATA ATTRIBUTE

02

GET DATASET IN JAVASCRIPT var color = document.getElementById ("demo").dataset.color;

TARGET HTML ELEMENT <div id="demo"></div>   GET HTML ELEMENT var el = document.getElementById("demo");

ARRAY IN DATA ATTRIBUTE

03

SET - JSON ENCODE ARRAY TO STRING el.dataset.arr = JSON.stringify(["R", "G", "B"]);   GET - JSON DECODE STRING TO ARRAY var data = JSON.parse(el.dataset.arr);