Custom attributes are among the most significant additions for HTML5, and can play a major role in semantic Web development. In this tutorial we’ll go through a practical example of creating and accessing HTML5 custom data attributes, including the necessary JavaScript functions.

It was possible before HTML5 to add your own attributes to HTML elements and access them using JavaScript, but if you’ve ever tried it you’ll know you can forget about getting your markup to validate. HTML5 provides the ability to create and use your own element attributes within valid pages.

Create Your HTML5 Document

If you don’t already have one you want to use, copy the following outline into an HTML file:

<!DOCTYPE html> <html> <head> <script> /*functions here*/ </script> </head> <body> </body> </html>

We will place our elements with custom attributes in the body and the JavaScript functions for accessing them in the head section script area.

Create an Element

Let’s add an element with some simple content and a custom attribute as well as an ID so that we can identify it in JavaScript for demonstration:

<div ;

To remove an attribute, you can also use either a DOM method or the dataset:

//DOM method theElement.removeAttribute('data-product-category');  //dataset version theElement.dataset.productCategory = null;

Conclusion

Implementing custom attributes in HTML5 is not technically complex in itself, however the real difficulty is in choosing whether it is appropriate to use them in your own projects, and if so how to go about it efficiently. Finally, do remember that it’s still a little early to start using the dataset approach for functions your pages rely on, so be sure to provide an alternative for non-supporting browsers.

相关文章: