Reputation: 13
I am working on a project that I need to change attribute of data-value by js language.
You can see the code here.
<div class="col-sm-4">
<div class="ldBar auto no-percent label-center m-auto" id="tree"
style="height: 300px; width: 300px;"
>>>>>>data-value="50"<<<<<<
data-type="fill" data-img="tree1.svg" data-fill="data:ldbar/res,bubble(#f00,#d00,100,1)"
data-fill-background="#ddd"
data-fill-background-extrude="0">
<svg xmlns:xlink="http://www.w3.org/1999/xlink"
preserveAspectRatio="xMidYMid" width="100%" height="100%" viewBox="-4.5 -4.5 109 109">
</svg>
<div class="ldBar-label"></div>
</div>
</div>
As it seems data-value is set 50. By this I am just making image fill up to 50 per cent. But I want to change this value automatically. A Js code that makes it lets say 25. How can have this access to change this value?
Upvotes: 0
Views: 2780
Reputation: 2947
This is simple pure-js example for read and write data-attributes:
var setDataAttribute = function() {
var dataContainer = document.getElementById('data-container');
var dataValue = parseInt(dataContainer.getAttribute('data-value'));
dataContainer.setAttribute('data-value', dataValue + 1);
dataContainer.innerHTML = dataValue + 1;
}
<div id="data-container" data-value="25">25</div>
<button onclick="setDataAttribute()">increase data value</button>
Upvotes: 1
Reputation: 68943
You can use jQuery's .data()
to get/set the attribute value:
$('#tree').data('value', '25');
console.log($('#tree').data('value')); // 25
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-sm-4">
<div class="ldBar auto no-percent label-center m-auto" id="tree" style="height: 300px; width: 300px;" data-value="50"
data-type="fill" data-img="tree1.svg" data-fill="data:ldbar/res,bubble(#f00,#d00,100,1)"
data-fill-background="#ddd"
data-fill-background-extrude="0">
<svg xmlns:xlink="http://www.w3.org/1999/xlink"
preserveAspectRatio="xMidYMid" width="100%" height="100%" viewBox="-4.5 -4.5 109 109">
</svg>
<div class="ldBar-label"></div>
</div>
</div>
Upvotes: 2