admin管理员组

文章数量:1327932

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");

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");
Share Improve this question edited Mar 1, 2017 at 8:47 uzr 1,2102 gold badges13 silver badges26 bronze badges asked Mar 1, 2017 at 8:22 nApSt3rnApSt3r 531 gold badge1 silver badge4 bronze badges 1
  • Are you running the code after the document has loaded? E.g. using window.onload or script at the bottom of the page? – RobG Commented Mar 1, 2017 at 8:51
Add a ment  | 

2 Answers 2

Reset to default 3

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>

Perhaps you are doing something else wrong because setAttribute() works. Could you post some more code? See for yourself:

var elem = document.getElementById("e2");

console.log(elem.getAttribute("data-transitiongoal"));
elem.setAttribute("data-transitiongoal", 10);
console.log(elem.getAttribute("data-transitiongoal"));
<div id="e2" class="progress-bar progress-bar-danger active" role="progressbar" data-transitiongoal="45">

本文标签: How to change HTML custom attribute value by JavaScriptStack Overflow