First, the basic concept
Added in HTML5 data- * way to customize the property, in fact, the so-called data- * attribute is data- prefix plus the name of the custom, the use of such a structure for data storage. Data- * Use current situation can be resolved without a custom property management chaos.
Second, a native custom attributes js
1, set custom properties
Custom properties provided the following two ways.
(1) The first way is to write directly above HTML tags:
< H2 the Data-weather Weather = "Rain" > fine today </ h2 >
The above data-weather is a custom attribute value rain.
In this way by the time set to be noted that, if a custom property set is a combination of multiple words, then, need to use the dash (-) links, such as:
< H2 the Data-Birth-DATE = "19,940,219" > fine today </ h2 >
(2) The second mode is set by the dataset attributes js:
// HTML <H2> nice day </ H2> // JS var H2 = document.querySelector ( 'H2' ); h2.dataset.weather = "Rain";
Such properties also set a custom data-weater, the value of rain, HTML5 elements will have attributes of a dataset, which is a type of key-value pairs DOMStringMap set.
In this manner also be noted that, if the set is a combination of a plurality of words, then, need to be written using the camel nomenclature:
// HTML <H2> nice day </ H2> // JS var H2 = document.querySelector ( 'H2' ); h2.dataset.birthDate = "19,940,219";
2, js read custom properties
When reading through the dataset property, use to get the custom attributes, you need to remove the data- prefix, a hyphen must be transformed into camelCase. "":
// HTML (setting) <= H2 Weather-Data "Rain" Data-Birth-DATE = "19,940,219"> fine today </ H2> // JS (read) var H2 = document.querySelector ( 'H2' ); console.log (h2.dataset.weather); // Rain console.log (h2.dataset.birthDate); // 19,940,219
3, css read custom properties
You can also write custom style attributes:
h3[data-birth-date="19940219"]{ color: red; }
The results are shown: