0

I have this

<div id="chart1" class="bar-chart secondary" data-total="42" animated>
<span class="bar-chart--inner" style="width:42%;"></span>
<span class="bar-chart--text">42% </span>
</div>

and I have one javascript variable var score that I need to assign to data-total="42"and <span class="bar-chart--text">42% </span> My intention is to replace 42 with my javascript variable. I have tried this document.getElementById("chart1").innerHTML =score that I have found from this forum but did not work. Please help.

<div id="chart1" class="bar-chart secondary" data-total="document.getElementById("chart1").innerHTML =score" animated>
    <span class="bar-chart--inner" style="width:42%;"></span>
    <span class="bar-chart--text">42% </span>
    </div>
7
  • You're setting a data attribute to a string; you'll want to put the JS somewhere where it'll actually execute, like in a script tag or event handler or something. Commented Sep 21, 2021 at 13:52
  • document.querySelector('.bar-chart--text').innerText = "52%" Commented Sep 21, 2021 at 13:53
  • @TJBlackman I have just tried it but didn't work. I guess I'm messing up where to place the <script> tags. My tags are in the header section. NB: I have very basic skills in Javascript Commented Sep 21, 2021 at 14:00
  • Put your JS Code to the end. Above the closing body tag. Commented Sep 21, 2021 at 14:03
  • Yes, the element does not exist yet if you put the script in the head. Commented Sep 21, 2021 at 14:04

1 Answer 1

6

https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes

get the element in a JS script

then set elem.dataset.total


document.getElementById("chart1").dataset.total = score

<body>
  <div id="chart1" class="bar-chart secondary" data-total="42" animated>
    <span class="bar-chart--inner" style="width:42%;"></span>
    <span class="bar-chart--text">42% </span>
  </div>
  <script type="text/javascript">
    var score = 20

    document.getElementById("chart1").dataset.total = score
  </script>
</body>

For setting the html of an element, you can use innerHTML, just need to select that element in another lookup.


document.querySelector(".bar-chart--text").innerHTML = score

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

1 Comment

This worked, Thank you!

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.