When should we use custom attributes in HTML?
HTML5 gives us so many attributes then why do developers go for custom attributes?
Use case :
- Create dynamic buttons using JavaScript.
- considering created buttons are in an array, print index of button clicked.
We will be starting with a code for creating dynamic buttons in HTML using JavaScript. To see how to create dynamic elements using JavaScript step by step, click here
We are using following code(figure 1, 2, 3) for the base.



Above code is similar to my previous article. Few changes are as follows -
- We are creating buttons instead of paragraphs
- markput for printing clicked button index in HTML
- and few classes, names changes
If it is still difficult to continue with this code then read How to create elements using JavaScript and come back.
In first part we won’t use custom attributes.
Our todo list -
- Add event for button clicks
- add some unique class/id for clicked event (we’ll add class)
- run a loop on buttons until we get the elements with the unique class.
- remove the unique class from button clicked.
- after coming out of loop the iterator variable with give you the index of button
- show that interator’s value in HTML

Figure 4 shows the equivalent code for our todo list with right side comments indicating step number in todo list.
A loop will run everytime we click on a button. So suppose we have 5000 buttons and if a user clicks on 4867'th button then the loop will iterate for 4867 times until it detects the unique class.
Now we’ll create custom attribute buttonIndex and save index value in it.
As shown in figure 5, we have created a global variable i with initial value 0(line no. 2). We assign i to buttonIndex attribute of newly created button(line no. 11) and then we increment i by 1 (line no. 12).

Now remaining task is simply to read buttonIndex attribute of clicked button and append it on HTML.

In this method, we didn’t use any loop so for 258454 buttons also, only a code of 4 lines will be executed for once.
In method 1(without cusotm attrbiute) and 2(with custom attribute), the resulting webpage will look exactly same as shown in figure 7.

Someone will say that we could have stored ButtonIndex in id/class or any other HTML5 attribute but those attributes aren’t meant to store indexes and it will be diffucult to understand code as class = “435 button mybutton” compared to class = “button mybutton” buttonIndex = “435” . Hence readability and optimization can be achieved in our use case when we have used custom attributes.
It is recommended that we should use HTML5 attributes wherever possible but if the code can be optimized to a considerable extent then I would recomment use off ustom attributes.