I declare a following div in file1.html to draw a nice gauge. The div uses some HTML5 Custom Data Attributes as follow:
JavaScript
x
10
10
1
<div class="gauge" id="meter1" data-settings='
2
{"value": 7,
3
"min": 0,
4
"max": 50,
5
"threshold": [
6
{"from": 25, "to": 50, "color": "blue", "label": "Warning"},
7
{"from": 0, "to": 25, "color": "orange", "label": "Critical"}
8
]
9
}'></div>
10
Now in Javascript, how do I recall the div and set new number for the “value” attribute and “threshold” attribute? Thanks
Advertisement
Answer
You can use following functions to fulfill your task:
element.getAttribute
to get the values inside the attributeelement.setAttribute
to set the values inside the attributeJSON.stringify
andJSON.parse
to work with JSON
Check the code below.
JavaScript
1
8
1
var meter1 = document.getElementById("meter1")
2
var dataSettings = JSON.parse(meter1.getAttribute("data-settings"))
3
dataSettings.value = 8
4
dataSettings.min = 5
5
6
meter1.setAttribute("data-settings", JSON.stringify(dataSettings))
7
8
console.log(meter1.getAttribute("data-settings"))
JavaScript
1
9
1
<div class="gauge" id="meter1" data-settings='
2
{"value": 7,
3
"min": 0,
4
"max": 50,
5
"threshold": [
6
{"from": 25, "to": 50, "color": "blue", "label": "Warning"},
7
{"from": 0, "to": 25, "color": "orange", "label": "Critical"}
8
]
9
}'></div>