Lesson 20

Data Attributes and Templates

In this lesson, you will look at two additional HTML5 features:

  • Data attributes: These allow you to define your own attributes on any element and thus bind data directly to the element. This has a number of useful purposes, as you will see shortly.
  • Templates: Templates are a relatively new HTML5 feature. They allow a document fragment to be created independently of the DOM itself. The document fragment can then be programmatically filled with data and added to the DOM. This will provide an alternative approach to the complex string concatenation used in the previous lesson.

Although this lesson introduces these two technologies together, there is no fundamental ­connection between them.

Template Tag

In the previous lesson, you used string concatenation to create a new row in the contacts table. As mentioned at the time, this is a problematic approach because it is very easy to make a ­mistake with the String concatenation.

A preferable approach to string concatenation is to define the structure of the HTML using regular tags but leave placeholders for the actual data. When you need to create a row, you could simply add data to this structure, and add it to the DOM. The template tag has been added to HTML5 to support this exact approach.

Get HTML5, JavaScript, and jQuery 24-Hour Trainer now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.