简体   繁体   中英

Data attribute on dynamically created elements

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:

  1. Use setAttribute : elCostPrice.setAttribute("data-num", i);

  2. Use dataset : elCostPrice.dataset.num = i;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM