Interestingly, each of the methods have slightly different performance results.
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. Obviously, the syntax is a little different for each property but they can be used to basically do the same thing: extract data.
Okay, so what’s the difference between the two? The answer is: not much. There are a couple of different ways to use Javascript to get a Data Attribute: How Can I Use Javascript to Get a Data Attribute?
Javascript getdata how to#
Now we’ve stored our data using Data Attributes, let’s take a look at how to access and use it. A data-product-link attribute which is going to contain a link to where the user can buy the product.A data-product- img attribute which is going to contain the location of the image we want to display.A data-product-title attribute, which is going to contain the name of our product.A data-target attribute, which we’re going to use to work out where we’re going to build our display.A data-link attribute to help us identify the link from the others (we’ll be adding more links later).Let’s take a look at the Data Attributes in a little more detail: We’re going to create links and a content area and the idea is we’re going to use the data we store in the above anchor tag’s Data Attributes to build our display. In our real-world example we’re going to be making a simple item picker using these HTML5 Data Attributes and Javascript. Some of these Data Attributes are out of context and are meaningless at this point, but others are a little more obvious. It has a standard HTML ID and Class, but as you can see it has a number of HTML5 Data Attributes too. In the example above, we have a regular HTML anchor tag. Let’s take a look at a real-world example of the HTML5 Data Attribute syntax and what you might use it for: Each HTML element can have any number of Data Attribute properties.Data Attributes will work on any HTML element.Custom Data Attributes should only really be used to store custom data and are not intended to replace existing HTML attributes and elements.Data tags should begin with the data- prefix and must contain at least one character after the hyphen.Let’s take a look at a couple of Data Attribute pointers / best practices directly from W3C to answer those questions: So what data can or should be stored using Data Attributes? What is the correct syntax to use? When should Data Attributes be used?