nApSt3r nApSt3r -4 years ago 187
HTML Question

How to change HTML custom attribute value by JavaScript?

I currently have this :

<div id="e2"
class="progress-bar progress-bar-danger active"
role="progressbar" data-transitiongoal="45">


And I want to change the data-transitiongoal value at run-time.

This doesn't work for me:

document.getElementById("e2").setAttribute("data-transitiongoal", "10");

Answer Source

As you told that you want to change at run time and you already tried one solution which will change it at loading itself, I suggest you the things.
Read this to understand and then only copy the below code.

  1. set a Timeout function which change the data and inside the function, clear the Timeout in order to avoid repetitive execution.
  2. set the duration in milliseconds such that after how much time you want to make the change. 2000 -> 2 seconds. 0 -> immediate ( seconds * 1000).

You can check the console and duration to detect when and where the change appeared.

console.log(document.getElementById('e2')); // log actual element -> 45
var SIT=window.setTimeout(function(){
  document.getElementById("e2").setAttribute("data-transitiongoal", "10");
  console.log(document.getElementById('e2'));
  window.clearTimeout(SIT);
},2000); // change duration
// log changed element -> 10
<div id="e2" class="progress-bar progress-bar-danger active" role="progressbar" data-transitiongoal="45">Something</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download