Employee Table

How You Can Use HTML5 Custom Data Attributes and Why

Data attributes allow developers to store custom data in HTML elements. They provide a way to add extra information to HTML elements that can be used by JavaScript or CSS to add functionality to a webpage. In this article, we will cover what data attributes are and what they are used for.

Why Custom Data Attributes?

Very often we need to store information associated with different DOM elements. This information might not be essential for readers, but having easy access to it would make life a lot easier for us developers.

For instance, let’s say you have a list of different restaurants on a webpage. Before HTML5, if you wanted to store information about the type of food offered by restaurants or their distance from the visitor, you would have used the HTML class attribute. What if you also needed to store the restaurant id to see which particular restaurant the user would want to visit?

Here are a few problems with the approach based on the HTML class attribute.

  • The HTML class attribute is not meant to store data like this. Its main purpose is to allow the developer to assign style information to a set of elements.
  • Each additional piece of information requires us to add a new class to our element. This makes it harder to parse the data in JavaScript to actually get what we need.
  • Let’s say a given class name begins with numbers. If you decide to later style the elements based on that data in the class name, you will have to either escape the number or use attribute selectors in your stylesheet.

To get rid of these issues, HTML5 has introduced custom data attributes. All attributes on an element whose name starts with data- are data attributes. You can also use these data attributes to style your elements.

Next, let’s dive into the basics of data attributes and learn how to access their values in CSS and JavaScript.

The HTML Syntax

As I mentioned earlier, the name of a data attribute will always start with data- . Here is an example:

li data-type="veg" data-distance="2miles" data-identifier="10318"> Salad King li>

You can now use these data attributes to search and sort restaurants for your visitors. For example, you can now show them all the vegetarian restaurants within a certain distance.

Besides the data- prefix, the name of a valid custom data attribute must contain only letters, numbers, hyphen (-), dot (.), colon (:) or underscore (_). It cannot contain capital letters.

There are two things that you should keep in mind when using data attributes.

First, data stored in these attributes should be of type string. Anything that can be string-encoded can be stored in data attributes as well. All the type conversions will need to be done in JavaScript.

Second, data attributes should only be used when there are no other appropriate HTML elements or attributes. For example, it is not appropriate to store an element’s class in data-class attribute.

An element can have any number of data attributes with any value you want.

Data Attributes and CSS

You can use data attributes in CSS to style elements using attribute selectors. You can also show the information stored in the data attribute to users (in a tooltip or some other way) with the help of the attr() function.

Styling Elements

Getting back to our restaurant example, you can give users a cue about the type of restaurant or its distance from them using attribute selectors to style the background of the restaurants differently. Here is an example:

li[data-type='veg']  background: #8BC34A; > li[data-type='french']  background: #3F51B5; >

Creating Tooltips

You can use tooltips to show users some additional information related to an element.

I recommend you use this method for quick prototypes rather than a production website, not least because CSS-only tooltips are not fully accessible.

The information that you want to show can be stored in a data-tooltip attribute.

span data-tooltip="A simple explanation">Wordspan>

You can then present the data to the user with the ::before pseudo element.

span::before  content: attr(data-tooltip); // More Style Rules > span:hover::before  display: inline-block; >

Accessing Data Attributes with JavaScript

There are three ways of accessing data attributes in JavaScript.

Using getAttribute and setAttribute

You can use getAttribute() and setAttribute() in JavaScript to get and set the value of different data attributes.

The getAttribute method will either return null or an empty string if the given attribute does not exist. Here is an example of using these methods:

let restaurant = document.getElementById("restaurantId"); let ratings = restaurant.getAttribute("data-ratings");

You can use the setAttribute method to modify the value of existing attributes or to add new attributes.

restaurant.setAttribute("data-owner-name", "someName");

Using the dataset Property

A simpler method of accessing data attributes is with the help of the dataset property. This property returns a DOMStringMap object with one entry for each custom data attribute.

There are a few things that you should keep in mind while using the dataset property.

It takes three steps to transform a custom data attribute into a DOMStringMap key:

  • The data- prefix is removed from the attribute name
  • Any hyphen followed by a lower case letter is removed from the name and the letter following it is converted to uppercase
  • Other characters will remain unchanged. This means that any hyphen that is not followed by a lowercase letter will also remain unchanged.

The attributes can then be accessed using the camelCase name stored in the object as a key like element.dataset.keyname .

Another way of accessing the attributes is using bracket notation, like element.datasetCss создать свой атрибут

Consider the following HTML:

li data-type="veg" data-distance="2miles" data-identifier="10318" data-owner-name="someName"> Salad King li>
var restaurant = document.getElementById("restaurantId"); var ratings = restaurant.dataset.ratings; restaurant.dataset.ratings = newRating; var owner = restaurant.dataset['ownerName']; restaurant.dataset['ownerName'] = 'newOwner';

This method is now supported in all major browsers and you should favor it over the previous method for accessing custom data attributes.

Using jQuery

You can also use the jQuery data() method to access data attributes of an element. Before jQuery version 1.6, you had to use the following code to access data attributes:

var restaurant = $("#restaurantId"); var owner = restaurant.data("owner-name"); restaurant.data("owner-name", "newName");

From version 1.6, jQuery started using the camelCase version of data attributes. Now, you can do the same thing using the following code:

var restaurant = $("#restaurantId"); var owner = restaurant.data("ownerName"); restaurant.data("ownerName", "newName");

You should know that jQuery also tries to internally convert the string obtained from a data attribute into a suitable type like numbers, booleans, objects, arrays and null.

var restaurant = $("#restaurantId"); var identifier = restaurant.data("identifier"); console.log(typeof identifier); // number

If you want jQuery to get the value of an attribute as a string without any attempt to convert it into other types, you should use jQuery’s attr() method.

jQuery only retrieves the value of data attributes the first time they are accessed. The data attributes are then no longer accessed or changed. All the changes that you make to those attributes are made internally and accessible only within jQuery.

Let’s assume you are manipulating the data attributes of the following list item:

li id="salad" data-type="veg" data-distance="2miles" data-identifier="10318"> Salad King li>

You can use the code below to change the value of its data-distance attribute:

var distance = $("#salad").data("distance"); console.log(distance); // "2miles" $("#salad").data("distance","1.5miles"); console.log(distance); // "1.5miles" document.getElementById("salad").dataset.distance; // "2miles"

As you can see, accessing the value of the data-distance attribute using vanilla JavaScript (not jQuery) keeps giving us the old result.

Conclusion

In this tutorial I have covered all the important things that you need to know about HTML5 data attributes. Besides creating tooltips and styling elements using attribute selectors, you can use data attributes to store and show users some other data like a notification about unread messages and so on.

Share This Article

Gajendar is a web developer with a keen interest in learning new things in web development. He has been developing websites for five years and occasionally writes tutorials on topics he feels confident about.

Источник

How to declare a custom attribute in HTML?

In this article, we will discuss how to declare a custom attribute in HTML. Custom attributes can be useful in HTML when you want to store some additional information that is not part of the standard HTML attributes. It allows for more flexibility and customization in HTML and can help make your code more maintainable and understandable.

Approaches

We have two different approaches to declaring a custom attribute in HTML including the following −

Let us look at each step in detail.

Approach: Using the «data- prefix method»

The first approach is to declare a custom attribute in HTML as “data- prefix”. we can define custom attributes by prefixing the attribute name with «data-«. You can create your own names for a custom attribute by using a prefix of your choice. This allows you to attach specific data to an HTML element, which can be easily targeted using CSS, JavaScript, or jQuery.

Example

Following is an example to declaring a custom attribute in HTML using “data- prefix”.

    h1 < color: blue; >th < color: red; >table < border-collapse: collapse; width: 100%; >th, td < padding: 5px; text-align: left; border-bottom: 1px solid #ddd; >tr:nth-child(even) 

Employee Table

Employee ID Name Department Salary
001 Taylor IT $75,000
002 Jhon HR $60,000

Note − Here, JavaScript can access the custom attributes in the example code by selecting the «tr» elements based on their custom attributes, and then logging the values of those attributes to the console.

Approach: Using the «custom prefix method»

The first approach is to declare a custom attribute in HTML as a “custom prefix”. In HTML, a custom prefix refers to creating custom attributes on HTML elements. The prefix can be any name of your choice that is added before the attribute name, and it can be used to add additional data or information to an element. By using a custom prefix, you can create your own custom attributes that are specific to your needs and can be targeted in CSS or JavaScript.

Example

Following is an example of declaring a custom attribute in HTML using “custom prefix”.

    [custom] 

Tutorials point

Hello World!

It defines a custom attribute named «custom» and applies the CSS style to any element with that attribute.The JavaScript code selects the header and paragraph elements based on their custom attributes and logs the values of those attributes.

Conclusion

In this article, we examined two different approaches to declare a custom attribute in HTML. Here, we are using two different approaches “data- prefix” and the “custom prefix”. Both custom prefix and data- prefix are used to declare custom attributes in HTML, but the dataprefix is more widely recognized and is supported by all modern browsers. The custom prefix is more flexible, as it allows you to choose your own prefix name, but it may not be recognized by all browsers or tools.

Источник

Читайте также:  Функция chmod в php
Оцените статью