How to assign dataset in Object.assign()?

Viewed 374

Is it possible to assign dataset attributes with Object.assign()? For example like this:

Object.assign(document.getElementById('test'), {
    id: 'test',
    dataset: { mydata: 'test' },
})

Update: at least this works for assigning multiple dataset:

Object.assign(document.getElementById('test').dataset, {
    mydata: 'test',
})
2 Answers

No.

The dataset property is readonly so you can't overwrite it.

If you could, then your attempt will break it because the value needs to be a DOMStringMap object and not a plain object.

You can use Element.setAttribute() function for adding HTMLElement attribtue. Check it out-

const el = document.getElementById('test');
const dataset = {name: 'john', age: 34, gender: 'male'};

for (const prop in dataset) {
    el.setAttribute(`data-${prop}`, dataset[prop]);
}
  • Here an object dataset with data name and value is declared.
  • Iterate throw the object using for ... in loop and using setAttribute function set the data attribtue.
Related