Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

246
Views
How to insert javascript variable in HTML div

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>
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!