最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to change HTML custom attribute value by JavaScript? - Stack Overflow

programmeradmin0浏览0评论

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

发布评论

评论列表(0)

  1. 暂无评论