Often I'm creating some kind of form on a website, and I have a <label> and a <input> which should be linked together.
The standard way to do this is by setting the 'for' attribute on the <label> to match the 'id attribute on the <input>
<label for="city-input">City</label>
<input id="city-input" type="text" />
This of course relies on having a unique ID for every <input> element on the page.
I frequently find myself in the situation where I have to create the form dynamically and the exact contents of the rest of the page are unknown or out of my control. So I can't just assign an id like 'city-input' in case it clashes with something else on the page. I end up creating random strings to use as ids:
var label = document.createElement('label');
label.innerHTML = 'City';
var input = document.createElement('input');
input.type = 'text';
// create a random string as the id
var id = Math.random().toString(36).substring(2);
input.id = id;
label.htmlFor = id;
This method works, but I hate it. I've got my HTMLInputElement instance and my HTMLLabelElement instance. I want to link them together. But I have to pointlessly create a random string to use as an intermediary. Then when someone clicks the <label> the browser has to pointlessly look up the string id to find the <input> element. It's so inelegant.
Is there any way to directly associate the HTMLLabelElement with the HTMLInputElement? Or some other better method?
(I know you can avoid the id by putting the <input> inside the <label> but this often isn't possible because of the way the page will be styled or various other reasons).