Vlad Merzhevich

What was sorely missing in HTML 4 was the ability to create your own attributes to store values. Why is this necessary? Here are a few tasks where this may be required.

  • Creating tooltips without using scripts.
  • Determine the style of an element based on an attribute value.
  • Receiving and changing values ​​through scripts.

HTML5 has a new universal attribute that can be added to any tag. The rules for writing an attribute are simple:

  • We always start with data-;
  • We use only Latin letters, hyphen (-), colon (:) and underscore (_).

CSS and JavaScript access these attributes slightly differently, so let's look at examples for them separately.

CSS

CSS has tag attributes; if there is any attribute or a given value, we set the required style.

Content

Now we can refer to this element as a div in styles and set the desired design for it. In general, this resembles how classes work, so it is not a unique or necessary feature. So it's more useful to set values.

Content

In CSS after this we can set different style for different values ​​of our data-columns attribute.

Div (width: 480px; ) div (width: 720px; )

Again, this is to some extent a replacement for classes; nothing prevents you from making classes with the names column-2, column-3 and adding them if necessary.

A more elegant application is to include the attr() function. It gets the value of the given attribute and inserts it into the style. It is convenient to use this to create tooltips. We write the text directly inside the element, and implement the display and design of the tooltip using CSS.

Tooltip meter ( position: relative; ) meter:hover::after ( content: attr(data-description); background: #ffe; padding: 5px; border: 1px solid #666; position: absolute; top: 20px; )

Water temperature

IN in this example the data-description attribute is added to the element containing the necessary text for display. The display itself occurs using the ::after pseudo-element and the content property, the value of which is the attr() function.

JavaScript

If in CSS we access the attribute name directly, specifying it in full, then in JavaScript this is done through the dataset method. The attribute name itself is converted into a variable according to the following rules:

  • data- discarded;
  • any hyphen preceding a letter is discarded, and the letter after it becomes capitalized.

In practice it looks like this.

data-description turns into description.
data-full-description becomes fullDescription.
data-description-of-tag becomes descriptionOfTag.

The traditional way to access an element and its attributes is to set an id and access the element via getElementById , as shown in the example below.

dataset User var el = document.getElementById("user"); id = el.dataset.id; // Get the value of the data-id attribute user = el.dataset.user; dob = el.dataset.dateOfBirth; // Get the value of the data-date-of-birth attribute el.dataset.ban = "No"; // Assign a new data-ban attribute and its value console.log(user); // Print the value of the variable to the console user console.log(dob); // Print the value of the dob variable to the console

First, we add an identifier with a unique value to the element. Then we access the element via getElementById . Now we can access any data attributes through the dataset method, and not only receive, but also set values. They will be stored until the page is reloaded or until a new value is set.

Before creating HTML5, work with attributes in HTML elements, to put it mildly, was not enjoyable. I had to use attributes like rel or class . And some developers even created their own attributes.

But things changed dramatically when HTML5 gave us the opportunity to use its data attributes. Now you can quite easily save additional data using standard tools.

How do date attributes work?

The name speaks for itself. Date attributes store some data specified by you. They always start with the prefix data- and end with something more understandable for the developer (according to the specification, only lowercase characters and hyphens are allowed). An element can contain any number of date attributes.

An example of using attributes to store user data:

  • Calvin
  • Of course, this data is not very helpful to the end user, since he simply does not see it, but date attributes are very widely used in modern web technologies.

    Here's an example of a button to delete something on your page:

    Delete

    All the necessary parameters are at your fingertips and ready to be sent to the backend script. No more rel attributes or processing the ID or required action from other attributes.

    What can you store?

    There is only one rule to remember: objects cannot be stored in date attributes. That is, it is possible if you serialize them first. For now, just remember that, in principle, you can only store string data.

    Reading/writing attributes using javascript

    Let's go back to the button example and see how we can access the required attributes.

    // This is a button var button = document.getElementById("your-button-id"); // Get the value var cmd = button.getAttribute("data-cmd"); var id = button.getAttribute("data-id"); // Change the value button.setAttribute("data-cmd", yourNewCmd); button.setAttribute("data-id", yourNewId);

    Pretty simple, right? Now simply pass the cmd and id parameters to your application and perform the necessary ajax request.

    Read/write date attributes using jQuery.

    Here's an analogue in jQuery:

    // Get the value var cmd = $("#your-button-id").attr("data-cmd"); var id = $("#your-button-id").attr("data-id"); // Change the value $("#your-button-id") .attr("data-cmd", yourNewCmd) .attr("data-id", yourNewId);

    Not to be confused with the data() method. Although they have some things in common, in general they are completely different things. Even if you are not completely familiar with these methods, just use attr() .

    Using the dataset API

    HTML5 even offers us an API for working with data attributes, although IE10 and below do not support it.

    Again, an example with a button, but this time using the dataset API:

    // This is a button var button = document.getElementById("your-button-id"); // Get the value var cmd = button.dataset.cmd; var id = button.dataset.id; // Change the value button.dataset.cmd = yourNewCmd; button.dataset.id = yourNewId;

    Please note the absence of the data prefix and hyphens. Just like when working with CSS properties in JavaScript, you will need the "humpback" case. The Dataset API translates attribute names so that data-some-attribute-name in HTML becomes dataset.someAttributeName in JavaScript.

    What can you do with date attributes?

    The examples given are just the foundation. You can do much more complex operations with date attributes. Let's look at a few examples.

    Filtration

    Let's say you're working with a list of elements and you need to filter them by keyword. Place keywords in the data attributes and use a small iterative script to process them.

    • Ford
    • Chevrolet
    • ...

    Example “on the knee”:

    $("#filter").on("keyup", function() ( var keyword = $(this).val().toLowerCase(); $(".cars > li").each(function() ( $(this).toggle(keyword.length< 1 || $(this).attr("data-models").indexOf(keyword) > -1); } ); } );

    Stylization

    Of course, it is better to apply styles using classes, but the same can be done using data attributes. This is how you can apply a style to elements that have a specific data attribute, regardless of its value. Let's look at the HTML first:

    And now the CSS:

    ( background: red; )

    But how do we take into account the value of an attribute? This is how you can apply a style to all elements with a data-warning attribute whose value contains the word error:

    ( color: red; )

    Settings

    The well-known Bootstrap framework uses data attributes to configure its JavaScript plugins. Popup example:

    Popover on top

    The best way to store data

    Date attributes are very common in web technologies. But the most important thing is that they are fully supported by older browsers and are penetrating deeper and deeper into web standards. And since the HTML standard has already been approved, you can work with them today and not be afraid that they will suddenly disappear tomorrow.