About custom data attributes

What are custom data attributes?

Newly introduced in HTML5, an attribute that specifies a unique attribute called custom data for the html element. You can also create original attributes. Custom data attribute names always start with ** data **. It can be used dynamically in various scripts, and is often used mainly when retrieving values ​​with JavaScript or jQuery.

<div class="tweet" data-genre="movie">
Attribute name: data-id
Attribute value: tweet.id

Originally, the purpose of the HTML class attribute is not to store data, but to assign style information such as CSS during development. However, as the information on the element increases, it becomes necessary to add a new class each time. In that case, it becomes difficult to extract the information actually required by JavaScript. Against this background, it was newly introduced in HTML5.

Custom data attribute rules

The rules for setting custom data attributes in HTML are as follows:

-Specify the attribute name after [x] ** data ** -[x] Attribute names can only use letters, numbers,-(hyphens),. (Dot), _ (underscore), not uppercase letters -[x] Attribute values ​​can be numbers or strings, but by convention most are lowercase -[x] class name cannot be stored as an attribute name (because data attributes should only be handled if there are no other suitable HTML elements or attributes)

How to use in JavaScript

Get data attributes

<div id="tweet" data-genre="movie"></div>
<script>
    var result = document.getElementById("tweet");
    var dataset = result.dataset;
    console.log(result);
</script>

Execution result

movie

Change data attributes

<div id="tweet" data-genre="movie"></div>
<script>
    var result = document.getElementById("tweet");
    result.dataset.genre = 'movie';
    console.log(result);
</script>

Execution result

movie

How to use with jQuery

Get data attributes

Specify the data attribute name in the argument like target element .data (attribute name).

<div class="tweet" data-genre="movie"></div>
<script>
    const result = $(".tweet").data('genre');
    console.log(result);
</script>

Execution result

movie

Change data attributes

<div class="tweet" data-genre="movie"></div>
<script>
    const result = $(".tweet").data('genre', 'movie');
    console.log(result);
    const result = $(".tweet").data('genre', 'music');
    console.log(result);
</script>

Execution result

movie
music

Recommended Posts

About custom data attributes
About =
Rails: A little summary about data types