dataset vs regular data methods.
Hey, what's the difference between using
dataset
and regular data methods such as setAttribute
? I know there's more to dataset
but i can't figure it out.
The only thing i see with dataset
is you can list all attribute names and values and have them put in an object but can't you also get attributes with .attributes
and .getAttribute
?
And for setting them rather than doing element.dataset.xyz = "xyz"
can't you use setAttribute
?
I'd appreciate any info. Thanks in advance.8 Replies
The use of dataset is for custom data attributes that you can put in the HTML. Use setAttribute for predefined attributes.
Oh okay, is there a specific reason for that sort of thing?
A specific reason for the split? Legacy. setAttribute predates custom data attributes
Yeah why you have to use one for one and one for the other. So essentially itβs just recommended in like the spec or something?
not sure, but dataset is just way more convenient and better practice. You never have to worry about mistyping
data-
for exampleah i see. So all in all it's basically the same as
getAttribute
and all the other ones, adding the object of course, but just for custom attributes instead?pretty much. Like Choo King said, just use dataset, and only use get/setAttribute for official HTML attributes
ah okay cool, thanks everyone