0

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

2 Answers 2

1

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>

Sign up to request clarification or add additional context in comments.

Comments

1

You can use document.querySelector with JSON.parse

const gauge = document.querySelector('#meter1');
 
console.log(JSON.parse(gauge.dataset.settings).threshold)
<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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.