The data property of the HTML 5 utility feature

Source: Internet
Author: User
Tags naming convention vcard

Before HTML 5, we had to rely on the class and REL attributes to store the pieces of data that needed to be used in the site, which sometimes created a conflict between the appearance and usefulness of the site. The existence of the HTML 5 Data property can be very satisfying.

The HTML5 standard allows you to embed a data-*-like attribute in a common element tag to enable access to some simple data. It is unlimited in number and can be dynamically modified by JavaScript, as well as CSS selectors for styling, and jquery provides support. This makes the data property particularly flexible and very powerful. With this property, we are able to make data presets or storage more orderly and intuitively.

For example, this is a span element whose content is the name of a piece of music, and we have more information on how to pre-provision the song directly in its HTML tag, and it looks like this can be written on the HTML source:

<span id="music-latch" class="musique"data-date="2013"data-genre="Electronic"data-album="Settle (Deluxe)"data-artist="Disclosure"data-composer="Howard Lawrence & Guy Lawrence">Latch (feat. Sam Smith)</span>

In this way, we will simply embed the album, artist and genre information directly into the span tag for this song.

Access datasets using GetAttribute, SetAttribute

As a label for HTML elements, the dataset's access is also subject to getattribute, SetAttribute, and the two methods are the most compatible.

For example, for the above two examples, we can run:

//getvar album = document.getElementById("music-latch").getAttribute("data-album");console.log(album);//setdocument.getElementById("food-pkd").setAttribute("data-en","Beijing Stuffed Duck");

This allows the dataset data to be accessed in a more compatible way. Any changes that are made can be reflected in real time to the element data property.

However, this method is relatively low-end, if you encounter multiple data-* custom fields, want to get all the data properties at once and wrapped into objects, you must also do a loop, very troublesome. But we also have a DataSet API available.

Accessing a DataSet using the dataset API

The value of the DataSet property is an instance of Domstringmap, a mapping of the name-value pairs. Each attribute in the Data-name form has a corresponding property, except that the property name does not have a data-prefix.

With the. DataSet API, it is easier to get all the data fields of an element and to make it easy to access and traverse in an object way. For example, for the example above, you can run:

//getvar songd = document.getElementById("music-latch").dataset;var album = songd.album;console.log(album);//setdocument.getElementById("food-pkd").dataset.en = "Beijing Stuffed Duck";//adddocument.getElementById("food-pkd").dataset.es = "Pato laqueado a la pekinesa";

When we access data, we don't need data-.dataset.name to access it. This is more convenient than the above method. Any changes that are made can be reflected in real time to the element data property.

If a hyphen is involved-a camel can be used to access:

<span id="en" data-en-us="Peiking Duck"></span>

Where en-us is to be written Enus:

var en = document.getElementById("en").dataset.enUs;

Accessing a DataSet using the Jquery.attr method

jquery has excellent compatibility. Similar to the GET, Setattribute,jquery. attr () method can also be used in such cases, for example, for the above example, you can run:

window.jQuery && (function($){//getvar album = $("#music-latch").attr("data-album");console.log(album);//set$("#food-pkd").attr("data-en","Beijing Stuffed Duck");})(window.jQuery);

This is exactly the same as when the jquery.attr is applied to other attributes, and any changes made can be reflected in real time to the element data property.

Accessing a DataSet using the Jquery.data method

jquery starts with the 1.4.2 version to support the $.data () method to access the data property directly, without having to write data-keywords, for example, for the above example, you can run:

window.jQuery && (function($){//getvar album = $("#music-latch").data("album");console.log(album);//set$("#food-pkd").data("en","Beijing Stuffed Duck");})(window.jQuery);

This method also has excellent access to the Data property, but it is important to note that the changes made to the Jquery.data data are not reflected in the HTML element on the database property.

That is , jquery now thinks that the data-en of the #food-pkd element is "Beijing stuffed Duck", but on the HTML element its value remains unchanged, still "Peking Duck":

window.jQuery && (function($){//set$("#food-pkd").data("en","Beijing Stuffed Duck");console.log( $("#food-pkd").data("en") );// log: "Beijing Stuffed Duck"})(window.jQuery);console.log( document.getElementById("food-pkd").dataset.en );// log: "Peking Duck"

Jquery.data parsing JSON information for a Dataset

In fact, jquery can also intelligently extract JSON information from data into objects:

<span id="song-jsn"data-meta=‘{"name":"Latch", "album":"Disclosure", "date":"2013"}‘>Latch (feat. Sam Smith)</span>window.jQuery && (function($){var jsn = $("#song-jsn").data("meta");console.log( jsn.album );// log: "Disclosure"})(window.jQuery);

This way, you don't have to write a bunch of data-album, data-lyrics, data-artist, you can just write all the song information in JSON and put it in a separate data tag!

CSS, jQuery find data property corresponding element

If I want all album names (Data-album) to be disclosure in red, in the CSS selector, we can match them like this:

.musique[data-album=‘Disclosure‘]{color:red;}

In this case, the span text in the above example will appear in red.

If I want all the now orderable foods to pop up after clicking, in jquery, you can also use the brackets [] to easily match in the following ways:

window.jQuery && (function($){$(".food").filter("[data-available]").each(function(){$(this).click(function(){alert("It‘s Available!");});});})(window.jQuery);

How does it feel that this kind of free and easy storage way can bring a very powerful effect.

How to use the Data property

The name of the custom data property must begin with data-, and at least one character that conforms to the HTML specification should be followed by a hyphen. (HTML naming convention.)

The data properties are described in the following document:

or application, for which there are no more appropriate attributes or elements.

This also means that we can only use data from within the application, and should not present it to the user. More importantly, you can customize any number of data properties to the element and give any meaningful value.

When do I need to use the Data property?

Through the above, you already know how to use the Data property. But to better understand this attribute, look at a few more examples.

The tuts+ webdesign plate already has a good example of using the Data property. One of the tuts, applying the data property to the style, gives the menu a "bubble" notification effect. In this example, the Data property is used for values that only want bubble notifications.

<a href="#" class="pink" data-bubble="2">Profile</a>

Another example: How the Quick Tip,data property is used as a cue box

<a href="#" class="tooltip" data-tip="this is the tip!">This is the link</a>

When should I not use the Data property?

The data property should not be used when an element has been established or is more appropriate. It is not appropriate to use data in the following example:

<span data-time="20:00">8pm<span>

Because in an element that represents time, there is already a DateTime attribute:

<time datetime="20:00">8pm</time>

At the same time, the data property should not be used as an alternative metadata or micro-format. The micro-format is primarily designed for humans to introduce contextual information. For example, if you have a vcard about an individual or an organization's contact information, you should give a class attribute called a vcard to let the machine know that it contains some contact information.

The code using the micro-format is as follows:

class="vcard">    <span class="fn " >Aaron Lumsden</span></div>

Instead, the code using the Data property is as follows:

<div class="vcard">    <span data-name="Aaron Lumsden " >Aaron Lumsden</span></div>

Learn more about micro-formats: mircorformats.org.

Using the Data property in CSS

Now that the Data property is implemented in HTML markup, you can also use this property in CSS. Note: Although it is more appropriate to use the Data property directly in some cases, it should not be used directly with any style rule. Simple to use as follows:

[data-role="page"] {  /* Styles */}
 html 5 dataset兼容性

The data property of the HTML 5 utility feature

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.