Use the element.dataset operation in HTML5 to customize data-* data:
Not long ago, I showed you a very useful classlist API, which is an interface that HTML5 the native CSS class for page elements to be added and censored, which can replace the CSS class operation methods in jquery. Another very useful API is the Element.dataset API, which has been supported since Firefox 6 and Chrome8. This simple API enables users get
or set
attributes on HTML page elements data-*
. Let's take a look at how it's used!
As you know, we can add custom attributes to HTML elements data-*
. You can give this attribute any name, but when using the Element.dataset API you need the following main rules:
- Element.dataset not be able to use directly, whether you will encounter error notification
data-*
when using a property name in JavaScript, turn the name into a camel-named (camel-case)
- Name cannot begin with XML
- Cannot have capital letters in the name
Suppose the following element exists in the page:
<divId= "Mydiv" data-name=" Mydiv "data-id=" myId "data-my-custom-key = "This is the value "> </div>
To get this data-id
property, your code should be written like this:
Get the element= document. getElementById("mydiv"); Get the id= element. DataSet. ID;
To get the data-my-custom-key
property value, your code should be written like this:
Retrieves "Data-my-custom-key"= element. DataSet. Mycustomkey;
The way to assign values to custom properties is this:
Sets the value to something elseelement. Datasets"Some other value"; Element would is://data-my-custom-key= "Some other value" ></div>
If a custom property does not exist, but you assign it to it in the program, it is automatically created:
Set new Data-attributeelement. DataSet"true"; Element would is://data-my-custom-key= "Some Other value" data-mootools-ftw= "true" >//</div>
You might think that data-*
objects can be stored in attributes, but in fact not, datasets do not initialize those objects. I'm not sure about the length of the dataset, but storing a lot of data in it must be the DOM becoming bloated and hard to debug. Friends who like to use jquery should know that there is a corresponding method in jquery, $.data()
Yes, this native dataset in HTML5 is to replace it, if your page simply needs to manipulate the data-*
custom properties, There is no need to introduce more and more of these jquery tools libraries, right?
Transferred from: http://www.webhek.com/element-dataset-api/
Turn: Element.dataset in HTML5