Interesting HTML (web API) Topics
Last updated on May 2022
WIP post, with some interesting topics about web APIs/HTML elements/etc.
Get the label for an input easily
I never knew that form elements such as <input>
(HTMLInputElement) has a labels
attribute, which is a list (DOMTokenList) of associated labels.
This is a demo, with the code below it:
The code is something along the lines of:
<!-- the label I want to get: -->
<label for="demo-email">Your email address</label>
<!-- the input I want the label for: -->
<input id="demo-email" />
<!-- button to trigger the alert() with the label textContent -->
<button id="show-label">Show label</button>
<script>
function clickHandler() {
// the <input> element:
const inputElement = document.getElementById('demo-email');
const labels = inputElement.labels; // << the bit i'm showing
const firstLabelElement = labels[0];
const labelText = firstLabelElement.textContent
alert(`Associated label for the input: "${labelText}"`);
}
document.querySelector('#show-label')
.addEventListener('click', clickHandler)
</script>