Skip to content
Advertisement

Change div content in HTML5 Custom Data Attributes

I declare a following div in file1.html to draw a nice gauge. The div uses some HTML5 Custom Data Attributes as follow:

<div class="gauge" id="meter1" data-settings='
   {"value": 7,
    "min": 0,
    "max": 50,
    "threshold": [
      {"from": 25, "to": 50, "color": "blue", "label": "Warning"},
      {"from": 0, "to": 25, "color": "orange", "label": "Critical"}
        ]
    }'></div>

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 attribute
  • element.setAttribute to set the values inside the attribute
  • JSON.stringify and JSON.parse to work with JSON

Check the code below.

var meter1 = document.getElementById("meter1")
var dataSettings = JSON.parse(meter1.getAttribute("data-settings"))
dataSettings.value = 8
dataSettings.min = 5

meter1.setAttribute("data-settings", JSON.stringify(dataSettings))

console.log(meter1.getAttribute("data-settings"))
<div class="gauge" id="meter1" data-settings='
   {"value": 7,
    "min": 0,
    "max": 50,
    "threshold": [
      {"from": 25, "to": 50, "color": "blue", "label": "Warning"},
      {"from": 0, "to": 25, "color": "orange", "label": "Critical"}
        ]
    }'></div>
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement