I am creating elements dynamically, this is the code i use for one cell.
I want to add a data attribute with a custom value.
I have tried:
elCostPrice.data-num = i;
elCostPrice.data["num"] = i;
elCostPrice.prop["num", i]
but none of those worked
var Cell3 = row.insertCell(3);
var elCostPrice = document.createElement('input');
elCostPrice.type = 'text';
elCostPrice.className = 'cost_price form-control required';
elCostPrice.name = 'cost_price' + i;
elCostPrice.id = 'cost_price' + i;
elCostPrice.placeholder = 'Cost Price';
elCostPrice.value = cost_price;
Cell3.appendChild(elCostPrice);
You need to use HTMLElement.dataset property
The
HTMLElement.dataset
property allows access, both in reading and writing mode, to all the custom data attributes (data-*) set on the element, either in HTML or in the DOM.
elCostPrice.dataset.num = i;
There are two ways:
Use setAttribute
: elCostPrice.setAttribute("data-num", i);
Use dataset
: elCostPrice.dataset.num = i;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With