Harness the power of HTML5 custom data via JavaScript API


Harness the power of HTML5 custom data via JavaScript API

Recipe ID: hsts-r65


When writing your HTML code, sometimes you need to add additional information about an item or a page element so that search engines will understand it better while hiding such info from site visitors. It can be achieved by HTML5 custom data attributes.  You can attach additional info to your webpage elements via custom data attributes that are invisible to your users. Adding custom data to your HTML markup has three benefits: 1- it improves your site’s User Experience or UX, 2- It reduces the amount of JavaScript or server-side code on your pages; thus, make your webpage more scalable, 3- It make your web pages more SEO friendly.


Project Files
Click here to download project source files. You can see its live demo too. 

Custom Data Overview

Html5 now gives us the ability to embed custom data attributes on all HTML elements. HTML5 custom data attributes have two parts:


Create Custom Data Attributes
When  you designing your web applications, you need to identify pages or sections in which you wish to use custom data. Then, define your own data- attributes to name and store the information as shown below:

<h1>Blockchain books</h1>
<ul>
<li data-year="2019" data-author="Brian Wu" data-pages="310">Hyperledger Cookbook</li>
<li data-year="2018" data-author="Brian Wu" data-pages="528">Blockchain by Example</li>
<li data-year="2018" data-author="Brian Wu" data-pages="222">Blockchain Quick Start</li>
<li data-year="2019" data-author="Brian Wu" data-pages="234">Security Tokens and Stablecoins Quick Start Guide</li>
</ul>

Tip: if you are using custom data on multiple sections of a webpage, make sure to all attribute names in a page are unique  so that your JavaScript code can properly differentiate them.


When a user clicks on a book, a new layer opens up in the browser displaying the additional info about book such as author, publication year, and total pages. By using the data- attributes that we have added to our <li> elements, we can now display this information instantly without having to worry about making any Ajax calls and without having to make any server-side database queries.

Back to our book list, since not everyone wants to see book details, we can hide book details like the publication year, author, and total pages of the book from viewers. With custom data attributes, we can include such irreverent data in the markup without requiring readers to look at it.
In order to store the publication year, author, and total pages of each book, in this example we created three custom data attributes: data-author, data-year, and data-pages.


As you can see, they all start with data- followed by at least one character. The name you define may not include uppercase letters, but it can include hyphens. You could, for example, define a data-month-year attribute (we discuss it in detail in the next section), but data-month|year would not be allowed.
Even though we use the three custom attributes consistently in this example, we haven’t created any special relationships by using them together—for example, we could list another book and apply only a data-author attribute, or we could go on to list podcasts that we have aired and reuse the data-author attribute . As a web designer, you can create and maintain structure or define the namespace you need for your website or application.

Tip: HTML5 custom data attributes should not be used as i- data attributes for existing attribute or element which is more appropriate for storing your data. For example, nav or progress data should probably be presented semantically in a nav or progress element instead rather than stored in custom data attributes, and ii- replacement for microformats since custom data is not intended to be publicly usable.

 

Access and Manipulate Custom Data with JavaScript

Now that we understand what custom data attributes are and when we can use them, we should probably take a look at how we can exploit their power with JavaScript. In this section, I review two JavaScript methods for getting and setting custom data attribute values. The first approach is very easy using native JavaScript, whereas the second one uses HTML5 JavaScript API property. In the next section, we show you how to use jQuery to access and change custom data.

If we want to fetch or update custom data attributes using existing, native JavaScript, all we need to do is to use the getAttribute and setAttribute methods as shown below:

<div id='blockchain-books' data-books='4' data-month-year='Feb 2019></div>

<script>
// 'Getting' data-attributes using getAttribute
var b= document.getElementById('blockchain-books');
var bookCount = b.getAttribute('data-books'); // bookCount = '12'

// 'Setting' data-attributes using setAttribute
books.setAttribute('data-books,'7'); //
</script>

This method will work in all modern browsers; however, you can accomplish more with JavaScript API.

The second and more advance way is to use HTML5 JavaScript APIs to access an element’s dataset property. This dataset property will return a DOMStringMap object of all the selected element's data- attributes. When using this approach, rather than using the full attribute name, you can bypass the data- prefix and refer to the custom data directly using the name you have assigned to it. To better understand how to use dataset, compare previous native JavaScript implementation with the below code. Major changes are the replacement of getAttribute and setAttribute with dataset.

<div id='blockchain-books' data-books='4' data-month-year='Feb 2019'></div>

<script>
// 'Getting' data-attributes using dataset
var b= document.getElementById('blockchain-books');
var total= b.dataset.books; // total books= 4;

// 'Setting' data-attributes using dataset
var y= b.dataset.monthYear; // 'month-year' => 'monthYear'
b.dataset.monthYear = 'March 2018';  // updating month and year
</script>

If, at some point in your script, a specific data- attribute becomes redundant and is no longer needed, it is also possible to completely remove that attribute from the DOM element by setting it to a value of null.

b.dataset.pages = null; // remove it

Now that you know how dataset works, we can move on doing more advance JavaScript coding. Start with the same markup as our previous section, but add a paragraph for JavaScript output:


<h1>Blockchain books</h1>
<ul>
<li data-year="2019" data-author="Brian Wu" data-pages="310">Hyperledger Cookbook</li>
<li data-year="2018" data-author="Brian Wu" data-pages="528">Blockchain by Example</li>
<li data-year="2018" data-author="Brian Wu" data-pages="222">Blockchain Quick Start</li>
<li data-year="2019" data-author="Brian Wu" data-pages="234">Security Tokens and Stablecoins Quick Start Guide</li>
</ul>

<p> </p>

Here is the JS codes that access the custom data using the dataset API:


<script>
var b= document.getElementsByTagName("li");
var output = "How many pages are books? ";

for (var i=0; i < b.length; i++)
{
output += b[i].dataset.pages;

if (i != (b.length-1))
{
output +=  ", "
}
}

document.getElementsByTagName("p")[0].innerHTML = output;
</script>

The JavaScript is straightforward: we create an array of all list items (books), and we create a string that is inserted into the paragraph (output). As we iterate over the books array, we use dataset.pages to access the value of each data-pages attribute and append it to the output variable. The end result is the phrase “How many pages are books? 310, 528, 222,234” being added to the paragraph at the end of the list.

Where dataset is not supported, simply use getAttribute(). Here is the for loop using fallback logic and getAttribute() when necessary:

 

for (var i=0; i < b.length; i++)
{
if (b[i].dataset)
{
output += b[i].dataset.pages;
}
else
{
output += b[i].getAttribute("data-pages");
}
if (i != (b.length-1))
{
output += ", ";
}
}

Access and Manipulate Custom Data with jQuery

The jQuery offers simple data() method for accessing and manipulating custom data. Let’s return to an earlier example to see how it works:


<ul>
<li data-year="2019" data-author="Brian Wu" data-pages="310">Hyperledger Cookbook</li>
</ul>

<script>
alert($("li").data("year"));        // alerts "2019"
alert($("li").data("author")); // alerts "Brian wu"

// change book publication year
$("li").data("year", "2017");

// and add the rating data
$("li").data("rating", "5 star");
</script>

The jQuery data() method successfully reads the data-year and data-author attributes defined in the markup, but if you access data-pages via the dataset API or examine the DOM object, you neither see its value change nor find a data-rating attribute, as you did in previous section.


<script>
alert($("li").data("pages")); // alerts "310"
alert(document.getElementsByTagName("li")[0].dataset.pages); // alerts "310"
</script>

While jQuery reads in the data from the custom data attributes, it does not write this data back to the DOM; instead, it stores the data in a JavaScript object. This speeds up applications where high volume of data access or manipulation is performed. However, if you forget this difference and try to also use the dataset API in your application, you will encounter some unexpected results.

Summary
In this tutorial, we reviewed HTML5 custom data and show you how to add it to  your web pages. We also discuss using JavaScripts in three ways for accessing and manipulating custom data attribute values- native JavaScript, HTML5 JavaScript API and jQuery. Now that you learn about custom data, think about how you can incorporate it into your next project.

 

Here is the list of other related tutorials that are highly recommended:



Here is the list of classes that are highly recommended:

 

Click here if you wish to learn more about training and career options available in the IT industry.


Private and Custom Tutoring

We provide private tutoring classes online and offline (at our DC site or your preferred location) with custom curriculum for almost all of our classes for $50 per hour online or $75 per hour in DC. Give us a call or submit our private tutoring registration form to discuss your needs.


View Other Classes!