Custom attributes in JavaScript

HTML allows you to add your own custom attributes to tags. Such attributes should start with data- followed by whatever attribute name you like.

Custom attributes can be used in a huge number of different ways. We will explore many of these methods later in the tutorial, and there are many more you can invent yourself later on.

Access to such attributes is not arranged in a standard way. You can't just refer to the element's property of the same name, as we did before, but you should use the special property dataset, after which the attribute name is written using a dot without data-. For example, if our attribute is called data-test, then to refer to it we will write elem.dataset.test, where elem is a variable with our element.

Let's look at an example. Let's say we have the following element:

<div id="elem" data-num="1000"></div>

Let's display the value of its data-num attribute:

let elem = document.querySelector('#elem'); console.log(elem.dataset.num); // shows 1000

Now let's assign this attribute a different value:

let elem = document.querySelector('#elem'); elem.dataset.num = 123;

Given the following code:

<div id="elem" data-text="str">text</div>

Make it so that when you click on the div, the content of its data-text attribute is added to the end of its text.

Given divs that contain their ordinal number in the data-num attribute:

<div data-num="1">text</div> <div data-num="2">text</div> <div data-num="3">text</div> <div data-num="4">text</div> <div data-num="5">text</div>

Make it so that when you click on any of the divs, its ordinal number is written to the end.

Given a button. Make it so that this button counts the number of clicks on it, writing them to some custom attribute. Let on click on another button on the screen displays how many clicks were done on the first button.

Given an input:

<input id="elem" data-length="5">

In this input, the data-length attribute contains the number of characters to be entered into the input. Make it so that when focus is lost, if the number of characters entered does not match the specified one, a message is displayed about this.

Given an input:

<input id="elem" data-min="5" data-max="10">

In this input, the attributes data-min and data-max contain a range. Make it so that when focus is lost, if the number of characters entered does not fall within this range, a message is displayed about this.

enru