Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data attribute on dynamically created elements

Tags:

javascript

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);
like image 745
charlie Avatar asked Apr 29 '17 14:04

charlie


2 Answers

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;
like image 99
Satpal Avatar answered Oct 12 '22 10:10

Satpal


There are two ways:

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

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

like image 9
T.J. Crowder Avatar answered Oct 12 '22 10:10

T.J. Crowder