How to correctly use the ID attribute
Implementation example: how to use the id to get inputs tab order implementation working
idattribute is a powerful feature that allow us to identify unequivocally an element in a page.
Caution: you cannot have more than one element with the same id in an HTML document.
- Apply styles via CSS
- Apply HTML attributes
It's simple if you only have 1 element to which you want to apply an id.
But, as you can't have the same
idfor different elements, what happens if you, for example, want to assign an
idto a reusable element that can appear several times in the same page?
You can create a variable in the reusable, that variable is going to be unique for each reusable instance, even in the same page. Using 'Calculate RandomString' you can have that unique value.
Let see the application in a real example:
In this case, we had a form in a popup with inputs and tooltips. The tooltips are a reusable element that appears a couple of times in the popup.
When the user try to move from one input to another using the keyboard, with the 'Tab' key, the tooltips, clickable elements, gained focus and the user had to press the 'Tab' key twice to go from an input to another when there was a tooltip in between.
- 1.In the reusable, create a variable = random string (will be unique for each instance of the reusable)
2. In the reusable, add the id, in this case we are going to use 'noTab' + our random variable (it could have been just the random string, but using it this way is more readable for other developers and it'll help in future app maintenance)
Adding the id
As you can see in the screenshot, we get the element using its
id, that would be unique. This was our code:
document.getElementById('noTabvar - tooltipId's text').setAttribute('tabindex', '-1');
4. Our popup working flawlessly: