Setting several properties of dataset of any DOM element, writing to the dataset property

{}
June 21st, 2022

One of the greatest additions in writing JS of the last years for writing clean code are arrow functions, classes and several ways of Destructuring assingment.

Arrow functions let you skip, several verbose terms like the function keyword, return keyword and {} character, while maintaining readability. Easy, once you mastered the new syntax!.

What is Destructuring assingment?

Let’s assume you fetch a stock json:

let json= {name:"SHELL PLC",isin:"GB00BP6MXD84",price:"25.00","volume":"2500000",time:"2022-06-22:09-06"}

They old way of dealing with this was to write everything out to assign values to variables:

var name = json.name;
var isin= json.isin
var price = json.price;
var volume=json.volume;
var time = json.time;

Destructuring assingment let you do this more succinct:

let {name,isin,price,volume,time}=json

That is nice code.

Destructuring arrays, or csv rows:

let {name,isin,price,volume,time}=row.split(",")

Sure there is more on parsing cvs rows than just splitting on “,” but this is an example and you get the drift. When you totally control the csv file, using “,” only as separator, it should do the job.

Writing to the datatset property?

I dearly miss something for setting the dataset property of an element concisely.

The dataset read-only property of the HTMLElement interface provides read/write access to custom data attributes (data-*) on elements.

Note: The dataset property itself can be read, but not directly written. Instead, all writes must be to the individual properties within the dataset, which in turn represent the data attributes.

So you can’t simply do something like this:

document.querySelector("#stock").dataset=json

You have to write it all out, and that isĀ  verbose:


let elStock = document.querySelector("#stock")
elStock.dataset.name=json.name;
elStock.isin=json.isin
elStock.price=json.price

Well there is a workaround.

Imitate writing to the dataset property directly, Object.assign()

According to the specs you can’t directly write the dataset, but you can do this:

Object.assign(document.querySelector("#stock"),json)

Result:

<body data-name="SHELL PLC" data-isin="GB00BP6MXD84" data-price="25.00" data-volume="2500000" data-time="2022-06-22:09-06">

A piece of cake. That is as easy as writing the dataset.property directly.

To extract dataset into variables destructuring assignment does work.

let {name,isin,price}=document.body.dataset

I used `Object.assign` in an older project for writing several properties to the style attribute, but it works as well for the dataset property.

Tags:

Leave a Reply