I have been using .getAttribute and today found out about .dataset, so i was wondering what the differences are and when should each be used.
So here is an example. Let's say we have a paragraph:
<p class="test" data-something="this is a test">some text</p>
if we use .getAttribute
let testText = document.querySelector('.test');
let testGetAttribute = testText.getAttribute('data-something');
console.log(testGetAttribute);
we get as output "this is a test".
if we use .dataset
let testText = document.querySelector('.test');
let testDataset = testText.dataset.something;
console.log(testDataset);
we also get "this is a test".
So, is there a difference between this two approaches? Are there some benefits in using one over the other?
Thank you!
Obviously, the syntax is a little different for each property but they can be used to basically do the same thing: extract data. The main difference is that the dataset property is solely for accessing custom data in Data Attribute, whereas the getAttribute property is to get data from any attribute within an HTML element.
We can either use the dataset property to get access to the data attributes or use the .getAttribute () method to select them by specifically typing their names. Here, in the below examples, we will use the getElementById () method that will return the elements havingthe given ID which is passed to the function.
The dataset JavaScript is a document-oriented module (DOM) property to access the data attribute and set it on the JavaScript element. It is a DOM interface to set data elements on the application using JavaScript language. It is a property to gives read-only access for data attributes but does not access write property directly.
The getAttribute () method is used to get the value of an attribute of the particular element. If the attribute exists, it returns the string representing the value of the corresponding attribute. If the corresponding attribute does not exist, it will return an empty string or null.
I'm only replying this because I faced a difference between the two methods that actually affected the functioning of my application.
I did getAttribute('data-id')
and dataset.id
to collect a todo item id
.
For getAttribute, if I ran through the debugger line by line, it worked fine. If I didn't, all sorts of wonky things would happen. For dataset.id it worked fine either way.
If you're curious about it, you can check lines 201 and 202 in my code: https://glitch.com/~wnc-reading-exercise-3 Comment out line 201 and uncomment line 201.
When running the app, try toggling complete on a todo item and see what happens to the DOM. If you go around toggling a few at a go you'll see some strange values show up.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With